SECONDS

SECONDS returns a count of the number of (whole) seconds the shell has been running. In the case of a shell script, this is the time that the script itself, not the shell which called it, has been running. If you change the value of SECONDS to another integer, it will keep counting from there. Setting SECONDS to a non-integer value will set it to zero. If you unset SECONDS, it will lose its special feature and become a regular variable, even if you later set it again.

SECONDS can be useful for a number of things, not only timing: If the shell script needs the occasional unique and not totally predictable number, it can always use (sleep 1; echo $SECONDS) to get a number not previously used by the current script. Another use for SECONDS is a result of the fact that the timeout(1) command returns the exit code of the command which it executed, unless it times out, in which case it returns 124. So there is no way to know if the command actually timed out, or if it returned the number 124 itself. SECONDS can help you to more accurately determine if the command timed out:

#!/bin/bash
SECONDS=0
timeout 60s slow_command
timeout_res=$?  
# 124 if timedout, but 124 could be the return code from slow_command
if [ "$SECONDS" -lt "60" ]; then
  # it did not time out; the value is from slow_command.
  echo "The command did not time out; it returned after $SECONDS seconds."
  cmd_res=$timeout_res
else
  # It timed out; take special action here
  echo "The command timed out."
fi

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.