How to do simple date (time) calculation in shell script?

Hi,

I'm looking for a way to do a simple math calc during a shell script as a means of logging how long a particular task takes.

For example...

STARTTIME=whenever this script starts
./path/to/command.sh >>logfile.log
TOTALTIME=<time at this stage of the script after above command finished> - $STARTTIME
ECHO This command took $TOTALTIME to complete. >>logfile.log

I know that's a crude representation, but hopefully enough to communicate what I'm looking to accomplish.

Thank you!!

Most shells have a SECONDS special variable you can use.

echo "Seconds since start of script:  $SECONDS"
sleep 10
echo "Seconds since start of script:  $SECONDS"

Wow. That's super easy. Is there away to format that number to minutes? A simple divide by 60 is all I need...

Depends on your shell, in BASH or KSH it's not hard:

printf "%02dH %02dM %02dS\n" $(( SECONDS/(60*60) )) $(( SECONDS/60 ))  $(( SECONDS%60 ))

And yet I couldn't find that by doing web searches. I do try before I post. Thank you SO much!

I tried to make that a variable in order to insert it into a sentence, and it didn't work.

#!/bin/bash

sleep 10

SCRIPTTIME= printf "%02dH %02dM %02dS\n" $(( SECONDS/(60*60) )) $(( SECONDS/60 ))  $(( SECONDS%60 ))

echo "This script took $SCRIPTTIME to run."


The output was:

00H 00M 10S
This script took  to run.

Variables don't work that way. You'd want to put it in `backticks` to put in in a variable.

Also, you don't want spaces after the equals sign. VARIABLE=something is good, VARIABLE=" something" is good, VARIABLE= something does something very different -- it blanks VARIABLE before attempting to run the program something...

But why not just jam it right into the printf statement, get it all done in one go?

printf "This script took %02dH %02dM %02dS to run\n" \
        $(( SECONDS/(60*60) )) $(( SECONDS/60 ))  $(( SECONDS%60 ))

The \ on the end of the line lets you continue it on the next line, instead of making one super-long line...

Using your logic.

STARTTIME=`date +"%s"`
./path/to/command.sh >>logfile.log
TOTALTIME=$(expr `date +"%s"`  - $STARTTIME)
ECHO This command took $TOTALTIME to complete. >>logfile.log

No problem. It's hard to know what to ask until you know at least a little... Check out the reference cards of the Advanced Bash Scripting Guide, they clear up some mysteries.