Elapsed Calculation in Bash Shell: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
(Created page with "Bash has a handy <code>SECONDS</code> builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties whe...")
 
No edit summary
 
Line 1: Line 1:
Bash has a handy <code>SECONDS</code> builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties when assigned to, and the value returned after the assignment is the number of seconds since the assignment plus the assigned value.
Bash has a handy <code>SECONDS</code> builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties when assigned to, and the value returned after the assignment is the number of seconds since the assignment plus the assigned value.


Thus, you can just set <code>SECONDS</code> to <code>0</code> before starting the timed event, simply read SECONDS after the event, and do the time arithmetic before displaying.
Thus, you can just set <code>SECONDS</code> to <code>0</code> before starting the timed event, simply read <code>SECONDS</code> after the event, and do the time arithmetic before displaying.


<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">

Latest revision as of 02:21, 12 November 2017

Bash has a handy SECONDS builtin variable that tracks the number of seconds that have passed since the shell was started. This variable retains its properties when assigned to, and the value returned after the assignment is the number of seconds since the assignment plus the assigned value.

Thus, you can just set SECONDS to 0 before starting the timed event, simply read SECONDS after the event, and do the time arithmetic before displaying.

SECONDS=0
# do some work
duration=$SECONDS
echo "$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."

As this solution doesn't depend on date +%s (which is a GNU extension), it's portable to all systems supported by Bash.