November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Categories

November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Elapsed Time for Shell Scripts

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:

T1=$(date +%s)
# Do something here
T2=$(date +%s)
diffsec="$(expr $T2 - $T1)"
echo | awk -v D=$diffsec '{printf "Elapsed time: %02d:%02d:%02d\n",D/(60*60),D%(60*60)/60,D%60}'

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.

 

#!/bin/bash

# Create function for calculating time difference.
function time_diff()
{
seconds=$(( $2 – $1 ))
hours=$((seconds / 3600))
seconds=$((seconds % 3600))
minutes=$((seconds / 60))
seconds=$((seconds % 60))
EX_TIME=`printf “%02d:%02d:%02d” $hours $minutes $seconds`

}

# Store the time before job start.
TIME1=`date +%s`

# Execute your command here. Taking sleep 10 as job right now.
sleep 10

# Store the time after finishing job.
TIME2=`date +%s`

# Pass the both the time to function
time_diff $TIME1 $TIME2

# EX_TIME will store the execution time of process.
echo “Execution time is $EX_TIME”

Simple BASH script example for showing the elapsed time for a script to execute:

#!/bin/bash

start_time=`date +%s`

end_time=`date +%s` time_elapsed=$(($end_time-$start_time))

echo “Script execution took $time_elapsed seconds.”

#!/bin/bash
NOW=$(date +"%d.%m.%Y")
FILE=/tmp/$NOW.log
df -ahl | grep -i sda1 > "$FILE"

 

Seeing “2 seconds” is fine, but I’m interested in it being “2.255322 seconds.” A better solution:
#!/bin/sh
START=`date +%s%N`

# Do stuff here

END=`date +%s%N`
ELAPSED=`echo “scale=8; ($END – $START) / 1000000000” | bc`

 

Shell Script to send email alerts when the server load average is more than 5

 

#!/bin/bash
avg=`uptime | awk ‘{print $8? ” $9 ” “$10 $11 $12 }’ | tr -s , ” “`
cur=`uptime | awk ‘{print $10}’ | tr -d , | cut -d. -f1`
str=”=============================”
info=”Curent $avg”

if [ $cur -ge 5 ]; then
info1=”Server load is high presently”
echo -e “$str\n$info\n$info1\n$str” | mail -s “Alert: Load Average for `hostname` on `date`” abc@yourdom.com
else
# echo -e “$str\n$info\n$str”
fi

 

 

1. Shell Script : Find All Zip / Rar Files Then Unzip / Unrar

Shell Script

Server1:~$ cat rar.sh

#!/bin/bash #this line must be in every bash script, just ensure that you use correct path

list=`find /home/yevhen/ -type f -name “*.rar”` # 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)

for line in $list; do # this line take every line from list to line variable

DEST=${line%/*} # remove from line filename, so just destination will be in DEST variable.

unrar x $line $DEST # unrar file from line variable to DEST dir

done # finish of for loop.

Output

    Server1:~$ ./rar.sh

UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal

Extracting from /home/yevhen/Dropbox/Yevhen/test.rar

Extracting /home/yevhen/Dropbox/Yevhen/wget.sh OK
All OK

UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal

Extracting from /home/yevhen/Pictures/test.rar

Extracting /home/yevhen/Pictures/wget.sh OK
All OK

===============================================30000
2. Shell Script To Check Disk Usage Is Out Of Space

Shell Script

#!/bin/bash

threshold=”20? # This set threshold value

i=2 #Counter, will be used later, set to 2, since first line in df output is description.

result=`df -kh |grep -v “Filesystem” | awk ‘{ print $5 }’ | sed ‘s/%//g’` # Getting list of percentage of all disks, df -kh show all disk usage, grep -v – without description line, awk ‘{ print $5 }’ – we need only 5th value from line and sed ‘s/%//g’ – to remove % from result.

for percent in $result; do # for every value in result we start loop.

if ((percent > threshold)) # compare, if current value bigger than threshold, if yes next lines.
then

partition=`df -kh | head -$i | tail -1| awk ‘{print $1}’` # taking name of partition, here we use counter. Df list of all partitions, head – take only $i lines from top, tail -1 take only last line, awk ‘{print $1}’ – take only first value in line.

echo “$partition at $(hostname -f) is ${percent}% full” #print to console – what partition and how much used in %.

fi # end of if loop

let i=$i+1 # counter increased by 1.

done # end of for loop.
Shell Script Result

Server:~/$ df -kh
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 52G 4.7G 45G 10% /
tmpfs 1.9G 0 1.9G 0% /lib/init/rw
udev 1.9G 192K 1.9G 1% /dev
tmpfs 1.9G 2.6M 1.9G 1% /dev/shm
/dev/sda6 92G 22G 66G 25% /home

Server:~/$ ./df_script.sh
/dev/sda6 at yevhen.lviv.example.com is 25% full

==========================================
3. Shell Script : Check Ping To Remote Host And Port Opened

Shell Script

Test Ping And Open Port

#!/bin/bash

# check if service name passed to script as argument, if there no arguments (0) do next

if [ “$#” = “0” ];

then

#write to terminal usage

echo “Usage: $0 ”

#since no arguments – we need to exit script and user re-run

exit 1
fi

#writing parameters to variables

host=$1
port=$2
email=”test@expertslogin.com”
subject=”Script result”

#Check if ping ok -q to quite mod, -c 4 for 4 checks

if ping -q -c 4 $host >/dev/null
then
# next lines writes result variable

ping_result=”OK”
else
ping_result=”NOT OK”

fi #end of fi loop

#next command check if port opened via nc command, and getting exit status of nc command

nc_result=`nc -z $host $port; echo $?`

#check of exit status of nc command, and write results to variables

if [ $nc_result != 0 ];
then
port_result=”not opened”
else
port_result=”opened”
fi #exit of fi loop

#writing message that script will email and write to output

message=”Ping to host – ${ping_result}, port $port ${port_result}.”

#next check if ping or port check is failed (ping if not OK and exit status of nc if not 0)

if [ “$ping_result” != “OK” -o “$nc_result” != “0” ];
then
echo “$message” #this line write warning message to terminal

echo “$message” | mail -s “$subject” $email #this line send email

fi

< h3=””>

Ping to localhost and check is 22 port opened (ssh server)

desktop:~/$ ./script 127.0.0.1 22
Ping to host – OK, port 22 not opened.
desktop:~/$

<>

===================================================

4. Shell Script : Service Status Check And start If It’s Not Running

Shell Script

#!/bin/bash

if [ “$#” = 0 ] # check if service name passed to script as argument, if there no arguments (0) do next

then
echo “Usage $0 ” #write to terminal usage

exit 1 #since no arguments – we need to exit script and user re-run it

fi

service=$1 #get service name from first argument

is_running=`ps aux | grep -v grep| grep -v “$0? | grep $service| wc -l | awk ‘{print $1}’` #this check
#if service running using ps command, after we remove our process from output, since script will also
# match, with wc we count number of matching lines .

if [ $is_running != “0” ] ; # is number of lines are not 0 do next

then

echo “Service $service is running” #just put this line to terminal

else #if number of precesses is 0

echo “Service $service is not running” #just put this string to terminal

initd=`ls /etc/init.d/ | grep $service | wc -l | awk ‘{ print $1 }’` #checking for files in /etc/init.d
#(directory with start-up scripts) with name similar to service

if [ $initd = “1” ]; #if there is script with similar name

then
startup=`ls /etc/init.d/ | grep $service` # this line get name of startup script (ls –
# lists files in directory

echo -n “Found startap script /etc/init.d/${startup}. Start it? Y/n ? ” #just put to
#terminal this line

read answer #waiting for user answer

if [ $answer = “y” -o $answer = “Y” ]; #if answer Y or y

then
echo “Starting service…”

/etc/init.d/${startup} start # running startup script

fi #exit of if loop

fi #exit of if loop

fi#exit of if loop

Results

server:~/$ ./service.sh apparmor
Service apparmor is not running
Found startap script /etc/init.d/apparmor. Start it? Y/n ? Y
Starting service…
* Starting AppArmor profiles [OK]

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>