{"id":2142,"date":"2013-07-06T11:37:30","date_gmt":"2013-07-06T03:37:30","guid":{"rendered":"http:\/\/rmohan.com\/?p=2142"},"modified":"2013-07-15T19:54:57","modified_gmt":"2013-07-15T11:54:57","slug":"elapsed-time-for-shell-scripts","status":"publish","type":"post","link":"https:\/\/mohan.sg\/?p=2142","title":{"rendered":"Elapsed Time for Shell Scripts"},"content":{"rendered":"<p>lot of times you want to calculate the time it takes for a part of a shell script to run. Here is one of the ways you can do this:<\/p>\n<pre>T1=$(date +%s)\r\n# Do something here\r\nT2=$(date +%s)\r\ndiffsec=\"$(expr $T2 - $T1)\"\r\necho | awk -v D=$diffsec '{printf \"Elapsed time: %02d:%02d:%02d\\n\",D\/(60*60),D%(60*60)\/60,D%60}'<\/pre>\n<p>This will tell you the elapsed time between setting T1 and setting T2. The output is formatted as HH:MM:SS and printed to the console. You can easily redirect to a file for logging.<\/p>\n<p>&nbsp;<\/p>\n<p>#!\/bin\/bash<\/p>\n<p># Create function for calculating time difference.<br \/>\nfunction time_diff()<br \/>\n{<br \/>\nseconds=$(( $2 &#8211; $1 ))<br \/>\nhours=$((seconds \/ 3600))<br \/>\nseconds=$((seconds % 3600))<br \/>\nminutes=$((seconds \/ 60))<br \/>\nseconds=$((seconds % 60))<br \/>\nEX_TIME=`printf &#8220;%02d:%02d:%02d&#8221; $hours $minutes $seconds`<\/p>\n<p>}<\/p>\n<p># Store the time before job start.<br \/>\nTIME1=`date +%s`<\/p>\n<p># Execute your command here. Taking sleep 10 as job right now.<br \/>\nsleep 10<\/p>\n<p># Store the time after finishing job.<br \/>\nTIME2=`date +%s`<\/p>\n<p># Pass the both the time to function<br \/>\ntime_diff $TIME1 $TIME2<\/p>\n<p># EX_TIME will store the execution time of process.<br \/>\necho &#8220;Execution time is $EX_TIME&#8221;<\/p>\n<p>Simple BASH script example for showing the elapsed time for a script to execute:<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>start_time=`date +%s`<\/p>\n<p>end_time=`date +%s` time_elapsed=$(($end_time-$start_time))<\/p>\n<p>echo &#8220;Script execution took $time_elapsed seconds.&#8221;<\/p>\n<pre>#!\/bin\/bash\r\nNOW=$(date +\"%d.%m.%Y\")\r\nFILE=\/tmp\/$NOW.log\r\ndf -ahl | grep -i sda1 &gt; \"$FILE\"<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Seeing \u201c2 seconds\u201d is fine, but I\u2019m interested in it being \u201c2.255322 seconds.\u201d A better solution:<\/strong><br \/>\n#!\/bin\/sh<br \/>\nSTART=`date +%s%N`<\/p>\n<p># Do stuff here<\/p>\n<p>END=`date +%s%N`<br \/>\nELAPSED=`echo &#8220;scale=8; ($END &#8211; $START) \/ 1000000000&#8221; | bc`<\/p>\n<p>&nbsp;<\/p>\n<h2>Shell Script to send email alerts when the server load average is more than 5<\/h2>\n<p>&nbsp;<\/p>\n<p>#!\/bin\/bash<br \/>\navg=`uptime | awk \u2018{print $8? \u201d $9 \u201d \u201c$10 $11 $12 }\u2019 | tr -s , \u201d \u201c`<br \/>\ncur=`uptime | awk \u2018{print $10}\u2019 | tr -d , | cut -d. -f1`<br \/>\nstr=\u201d=============================\u201d<br \/>\ninfo=\u201dCurent $avg\u201d<\/p>\n<p>if [ $cur -ge 5 ]; then<br \/>\ninfo1=\u201dServer load is high presently\u201d<br \/>\necho -e \u201c$str\\n$info\\n$info1\\n$str\u201d | mail -s \u201cAlert: Load Average for `hostname` on `date`\u201d\u00a0<a href=\"mailto:abc@yourdom.com\" target=\"_blank\" rel=\"nofollow\">abc@yourdom.com<\/a><br \/>\nelse<br \/>\n# echo -e \u201c$str\\n$info\\n$str\u201d<br \/>\nfi<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p><b>1. Shell Script : Find All Zip \/ Rar Files Then Unzip \/ Unrar<\/b><\/p>\n<p>Shell Script<\/p>\n<p><b>Server1:~$ cat rar.sh<\/b><\/p>\n<p>#!\/bin\/bash #this line must be in every bash script, just ensure that you use correct path<\/p>\n<p>list=`find \/home\/yevhen\/ -type f -name \u201c*.rar\u201d` # get list of file and write this list to variable with name list, find command used to find all files (-type f) where name match *.rar (-name key)<\/p>\n<p>for line in $list; do # this line take every line from list to line variable<\/p>\n<p>DEST=${line%\/*} # remove from line filename, so just destination will be in DEST variable.<\/p>\n<p>unrar x $line $DEST # unrar file from line variable to DEST dir<\/p>\n<p>done # finish of for loop.<\/p>\n<p><b>Output<\/b><\/p>\n<p><b>\u00a0\u00a0\u00a0 Server1:~$ .\/rar.sh<\/b><\/p>\n<p>UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal<\/p>\n<p>Extracting from \/home\/yevhen\/Dropbox\/Yevhen\/test.rar<\/p>\n<p>Extracting \/home\/yevhen\/Dropbox\/Yevhen\/wget.sh OK<br \/>\nAll OK<\/p>\n<p>UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal<\/p>\n<p>Extracting from \/home\/yevhen\/Pictures\/test.rar<\/p>\n<p>Extracting \/home\/yevhen\/Pictures\/wget.sh OK<br \/>\nAll OK<\/p>\n<p>===============================================30000<br \/>\n<b>2. Shell Script To Check Disk Usage Is Out Of Space<\/b><\/p>\n<p>Shell Script<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>threshold=\u201d20? # This set threshold value<\/p>\n<p>i=2 #Counter, will be used later, set to 2, since first line in df output is description.<\/p>\n<p>result=`df -kh |grep -v \u201cFilesystem\u201d | awk \u2018{ print $5 }\u2019 | sed \u2018s\/%\/\/g\u2019` # Getting list of percentage of all disks, df -kh show all disk usage, grep -v \u2013 without description line, awk \u2018{ print $5 }\u2019 \u2013 we need only 5th value from line and sed \u2018s\/%\/\/g\u2019 \u2013 to remove % from result.<\/p>\n<p>for percent in $result; do # for every value in result we start loop.<\/p>\n<p>if ((percent &gt; threshold)) # compare, if current value bigger than threshold, if yes next lines.<br \/>\nthen<\/p>\n<p>partition=`df -kh | head -$i | tail -1| awk \u2018{print $1}\u2019` # taking name of partition, here we use counter. Df list of all partitions, head \u2013 take only $i lines from top, tail -1 take only last line, awk \u2018{print $1}\u2019 \u2013 take only first value in line.<\/p>\n<p>echo \u201c$partition at $(hostname -f) is ${percent}% full\u201d #print to console \u2013 what partition and how much used in %.<\/p>\n<p>fi # end of if loop<\/p>\n<p>let i=$i+1 # counter increased by 1.<\/p>\n<p>done # end of for loop.<br \/>\n<b> Shell Script Result<\/b><\/p>\n<p>Server:~\/$ df -kh<br \/>\nFilesystem Size Used Avail Use% Mounted on<br \/>\n\/dev\/sda1 52G 4.7G 45G 10% \/<br \/>\ntmpfs 1.9G 0 1.9G 0% \/lib\/init\/rw<br \/>\nudev 1.9G 192K 1.9G 1% \/dev<br \/>\ntmpfs 1.9G 2.6M 1.9G 1% \/dev\/shm<br \/>\n\/dev\/sda6 92G 22G 66G 25% \/home<\/p>\n<p>Server:~\/$ .\/df_script.sh<br \/>\n\/dev\/sda6 at yevhen.lviv.example.com is 25% full<\/p>\n<p>==========================================<br \/>\n<b>3. Shell Script : Check Ping To Remote Host And Port Opened<\/b><\/p>\n<p>Shell Script<\/p>\n<p>Test Ping And Open Port<\/p>\n<p>#!\/bin\/bash<\/p>\n<p># check if service name passed to script as argument, if there no arguments (0) do next<\/p>\n<p>if [ &#8220;$#&#8221; = &#8220;0&#8221; ];<\/p>\n<p>then<\/p>\n<p>#write to terminal usage<\/p>\n<p>echo \u201cUsage: $0 \u201d<\/p>\n<p>#since no arguments \u2013 we need to exit script and user re-run<\/p>\n<p>exit 1<br \/>\nfi<\/p>\n<p>#writing parameters to variables<\/p>\n<p>host=$1<br \/>\nport=$2<br \/>\nemail=\u201dtest@expertslogin.com\u201d<br \/>\nsubject=\u201dScript result\u201d<\/p>\n<p>#Check if ping ok -q to quite mod, -c 4 for 4 checks<\/p>\n<p>if ping -q -c 4 $host &gt;\/dev\/null<br \/>\nthen<br \/>\n# next lines writes result variable<\/p>\n<p>ping_result=\u201dOK\u201d<br \/>\nelse<br \/>\nping_result=\u201dNOT OK\u201d<\/p>\n<p>fi #end of fi loop<\/p>\n<p>#next command check if port opened via nc command, and getting exit status of nc command<\/p>\n<p>nc_result=`nc -z $host $port; echo $?`<\/p>\n<p>#check of exit status of nc command, and write results to variables<\/p>\n<p>if [ $nc_result != 0 ];<br \/>\nthen<br \/>\nport_result=\u201dnot opened\u201d<br \/>\nelse<br \/>\nport_result=\u201dopened\u201d<br \/>\nfi #exit of fi loop<\/p>\n<p>#writing message that script will email and write to output<\/p>\n<p>message=\u201dPing to host \u2013 ${ping_result}, port $port ${port_result}.\u201d<\/p>\n<p>#next check if ping or port check is failed (ping if not OK and exit status of nc if not 0)<\/p>\n<p>if [ &#8220;$ping_result&#8221; != &#8220;OK&#8221; -o &#8220;$nc_result&#8221; != &#8220;0&#8221; ];<br \/>\nthen<br \/>\necho \u201c$message\u201d #this line write warning message to terminal<\/p>\n<p>echo \u201c$message\u201d | mail -s \u201c$subject\u201d $email #this line send email<\/p>\n<p>fi<\/p>\n<p>&lt; h3=&#8221;&#8221;&gt;<\/p>\n<p>Ping to localhost and check is 22 port opened (ssh server)<\/p>\n<p>desktop:~\/$ .\/script 127.0.0.1 22<br \/>\nPing to host \u2013 OK, port 22 not opened.<br \/>\ndesktop:~\/$<\/p>\n<p>&lt;&gt;<\/p>\n<p>===================================================<\/p>\n<h2><a title=\"Permanent Link to Shell Script : Service Status Check And start If It\u2019s Not Running\" href=\"http:\/\/www.expertslogin.com\/shell-script-2\/script-check-service-up\/\" rel=\"bookmark\">4. Shell Script : Service Status Check And start If It\u2019s Not Running<\/a><\/h2>\n<p>Shell Script<\/p>\n<p>#!\/bin\/bash<\/p>\n<p>if [ &#8220;$#&#8221; = 0 ] # check if service name passed to script as argument, if there no arguments (0) do next<\/p>\n<p>then<br \/>\necho \u201cUsage $0 \u201d #write to terminal usage<\/p>\n<p>exit 1 #since no arguments \u2013 we need to exit script and user re-run it<\/p>\n<p>fi<\/p>\n<p>service=$1 #get service name from first argument<\/p>\n<p>is_running=`ps aux | grep -v grep| grep -v \u201c$0? | grep $service| wc -l | awk \u2018{print $1}\u2019` #this check<br \/>\n#if service running using ps command, after we remove our process from output, since script will also<br \/>\n# match, with wc we count number of matching lines .<\/p>\n<p>if [ $is_running != &#8220;0&#8221; ] ; # is number of lines are not 0 do next<\/p>\n<p>then<\/p>\n<p>echo \u201cService $service is running\u201d #just put this line to terminal<\/p>\n<p>else #if number of precesses is 0<\/p>\n<p>echo \u201cService $service is not running\u201d #just put this string to terminal<\/p>\n<p>initd=`ls \/etc\/init.d\/ | grep $service | wc -l | awk \u2018{ print $1 }\u2019` #checking for files in \/etc\/init.d<br \/>\n#(directory with start-up scripts) with name similar to service<\/p>\n<p>if [ $initd = &#8220;1&#8221; ]; #if there is script with similar name<\/p>\n<p>then<br \/>\nstartup=`ls \/etc\/init.d\/ | grep $service` # this line get name of startup script (ls \u2013<br \/>\n# lists files in directory<\/p>\n<p>echo -n \u201cFound startap script \/etc\/init.d\/${startup}. Start it? Y\/n ? \u201d #just put to<br \/>\n#terminal this line<\/p>\n<p>read answer #waiting for user answer<\/p>\n<p>if [ $answer = &#8220;y&#8221; -o $answer = &#8220;Y&#8221; ]; #if answer Y or y<\/p>\n<p>then<br \/>\necho \u201cStarting service\u2026\u201d<\/p>\n<p>\/etc\/init.d\/${startup} start # running startup script<\/p>\n<p>fi #exit of if loop<\/p>\n<p>fi #exit of if loop<\/p>\n<p>fi#exit of if loop<\/p>\n<p>Results<\/p>\n<p>server:~\/$ .\/service.sh apparmor<br \/>\nService apparmor is not running<br \/>\nFound startap script \/etc\/init.d\/apparmor. Start it? Y\/n ? Y<br \/>\nStarting service\u2026<br \/>\n* Starting AppArmor profiles [OK]<\/p>\n","protected":false},"excerpt":{"rendered":"<p>lot of times you want to calculate the time it takes for a part of a shell script to run. Here is one of the ways you can do this:<\/p>\n<p> T1=$(date +%s) # Do something here T2=$(date +%s) diffsec=&#8221;$(expr $T2 &#8211; $T1)&#8221; echo | awk -v D=$diffsec &#8216;{printf &#8220;Elapsed time: %02d:%02d:%02d\\n&#8221;,D\/(60*60),D%(60*60)\/60,D%60}&#8217; <\/p>\n<p>This will tell you [&#8230;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[47],"tags":[],"_links":{"self":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/2142"}],"collection":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2142"}],"version-history":[{"count":10,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/2142\/revisions"}],"predecessor-version":[{"id":2346,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/2142\/revisions\/2346"}],"wp:attachment":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2142"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2142"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2142"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}