Question

I am writing a shell script to track the start&end time of some running programs. I need the script to print both the readable start&end time and the time cost in seconds at last.

To calculate the cost, I write something like this

START=$(date +%s)
# ................
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Start Time: $START"  >> $LOGFILE 2>&1
echo "End Time: $END" >> $LOGFILE 2>&1
echo "Running time: $DIFF seconds"  >> $LOGFILE 2>&1

This works for calculation, but the $START and $END can only be printed as number of seconds.

It's able to print readable date format if I define them like below

START=$(date +%c)
END=$(date +%c)

However, DIFF=$(( $END - $START )) doesn't work for them any more.

Therefore, I'm wondering if there're any solutions in shell script so that I can both print the date in defined format and do some calculations with them.

BTW, I am using AIX.

Was it helpful?

Solution

If you have GNU date, you can use the epoch time

date -d @$START +%c

Otherwise, do

read start start_display < <(date +"%s %c")
# ...
read end end_display < <(date +"%s %c")
diff=$(( $end - $start ))
echo "Start time: $start_display"

If you're not using a shell capable of process substitution,

set -- $(date +"%s %c")
start=$1; shift
start_display=$*

If you use bash, take advantage of the builtin $SECONDS variable, which starts at zero for a new bash process and increments each second.

start_display=$(date)
# ...
echo "Start Time: $start_display"
echo "End Time: $(date)"
echo "Running time: $SECONDS seconds"

OTHER TIPS

You can use date -d @Seconds to convert seconds to date. eg:

 $ date +%s
     1377095983
 $ date -d @1377095983
     Wed Aug 21 20:09:43 IST 2013
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top