How do I use $SECONDS inside a bash script?

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.


Solution 1:

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

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

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

Solution 2:

You've referenced the bash internal variable SECONDS (which outputs the number of seconds elapsed since the current instance of shell is invoked) and saved the value as another variable time_spent. Now, after that every time you check the value of variable time_spent, you would get the same value -- the saved one, at the time of expansion of SECONDS.

To dynamically get SECONDS, you should reference $SECONDS directly rather than using an intermediate variable:

echo "Time: $SECONDS"

If you insist on using an intermediate variable, make sure to do the expansion of $SECONDS every time.


Regarding the value of SECONDS being 0, you can easily reproduce this:

% bash -c 'echo $SECONDS'
0

The point is: when you're calculating the value, it's not a second yet, so the value is being 0, correctly.