Save in a variable the number of seconds a process took to run

Are you wanting to put this code in your script, or do it from the process that starts the script?

For the latter, you can use the "time" reserved word and then parse what it returns to get how much time a script takes.

If you want to do this from within a script you can set the variable SECONDS to zero, and each time thereafter that you reference that variable it will be updated to be the number of elapsed seconds. So, you can put "SECONDS=0" at the very start of your script, and whenever you need the elapsed time it will be in the SECONDS variable.

You can also use the $SECONDS trick on the command line as well, for example:

$ SECONDS=0; sleep 5 ; echo "that took approximately $SECONDS seconds"

The time reserved word and the SECONDS variable are both documented in the bash man page.


This works in Bash, and also Zsh:

# Set time format to seconds
TIMEFORMAT=%R
# Time a process
PROC_TIME=$(time (insert command here >/dev/null 2>&1) 2>&1)
echo $PROC_TIME
  • The first two redirections hide your process's output ">/dev/null 2>&1"
  • The last redirect is needed because "time" prints the time on stderr

Tags:

Linux

Time

Bash