Ubuntu – How to use $SECONDS inside a bash script

bashscripts

I want to save the result of the $SECONDS command into a variable, to print time in format HH:MM:SS.

This is what I've tried so far. I tried to print it in different ways and was always getting the result as 0:

time_spent="$SECONDS"
echo "Time: $time_spent"

I want to print time spent in the shell when I close my console. I created a script that runs every time the console was closed.

Best Answer

To get $SECONDS into HH:MM:SS format you will need to do some (integer) math:

$ hrs=$(( SECONDS/3600 )); mins=$(( (SECONDS-hrs*3600)/60)); secs=$(( SECONDS-hrs*3600-mins*60 ))

$ printf 'Time spent: %02d:%02d:%02d\n' $hrs $mins $secs
Time spent: 431:48:03