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.
To get
$SECONDS
into HH:MM:SS format you will need to do some (integer) math:You've referenced the
bash
internal variableSECONDS
(which outputs the number of seconds elapsed since the current instance of shell is invoked) and saved the value as another variabletime_spent
. Now, after that every time you check the value of variabletime_spent
, you would get the same value -- the saved one, at the time of expansion ofSECONDS
.To dynamically get
SECONDS
, you should reference$SECONDS
directly rather than using an intermediate variable:If you insist on using an intermediate variable, make sure to do the expansion of
$SECONDS
every time.Regarding the value of
SECONDS
being0
, you can easily reproduce this:The point is: when you're calculating the value, it's not a second yet, so the value is being
0
, correctly.If you're sure that
$SECONDS
will be less than 1 day (i.e. 86400 seconds), then GNU core-utilsdate
does a pretty good job of the required formatting:Here is a quick one that gives hours minutes and seconds since the shell has been opened:
Since scripts run in a subshell, the best way to get output is to source the script instead of calling it.
Examples:
Without sourcing the script
With sourcing the script
Hope this helps!