Click to See Complete Forum and Search --> : bash programming question concerint $(time)


hetman
06-09-2002, 12:45 PM
anyone know how to write a script that at the end would echo how long it took to execute?
echo "$(time?????)
thanks
i want to know how many seconds or min:sec it took to run.

stiles
06-09-2002, 01:33 PM
date +%s > /tmp/whatever_file

<body_of_script>

date +%s >> /tmp/whatever_file
VAL1=$(tail -n 1 /var/log/cam_check_time)
VAL2=$(tail -n 2 /var/log/cam_check_time | /usr/bin/cut -d "
" -f 1)
STIME=$(echo $VAL1-$VAL2 | bc)
rm /tmp/whatever_file


$STIME should be the time in seconds

hetman
06-09-2002, 01:38 PM
would this work just by running the script, or does it time how long a process took to execute?

i am writing a backup script which copies files from certain dirs into another dir and at the end of the script i want to echo time time it took to complete the operation.

so i want the time calculation to be called from the bash script... and not like
time -f %S myscript
i know the above would work but thats not what im looking for

l01yuk
06-10-2002, 07:23 AM
could use
date | awk '{print $4}' | awk -F: '{print ($1*60*60)+($2*60)+$3}'
which will work unless you click over from 12:XX to 01:00 at any point during the bakup.

Strogian
06-10-2002, 06:19 PM
How about using the $SECONDS variable? That just returns however many seconds have elapsed since bash (i.e. your script) was initiated, right?

dchidelf
06-10-2002, 09:20 PM
You can grap the unix time (seconds since 01/01/1970) at the start of execution and subtract it from the time at the end of execution. That will give the the number of seconds the backup took.

A fairly portable way to get the unix time is using the date command.
date +%s

#!/usr/bin/ksh

START=`/bin/date +%s`
# code
END=`/bin/date +%s`
DUR=$(($END-$START))
TIME=`/usr/bin/printf "%02d:%02d:%02d" $(($DUR/3600)) $(($DUR/60%60)) $(($DUR%60))`
echo It took $TIME

Using the unix time, you don't have to worry about time flipping from 23:59:59 to 00:00:00 because unix time continues to count up...until the year 2038 sometime when 32-bit unix runs out of bits...but you'll have more problems than timing backups at that point.