How to use a timer in bash?

If you want the duration in seconds, at the top use

start=$SECONDS

and at the end

duration=$(( SECONDS - start ))

You could use Linux's built-in time command. From the man page:

time COMMAND [arguments]

time determines which information to display about the resources used by the COMMAND from the string FORMAT. If no format is specified on the command line, but the TIME environment variable is set, its value is used as the format.

To time the cleanup.sh script, use:

$ time cleanup.sh

I realise this is a pretty old question but this is the way I do it for anything when I want/need to know how long something took to run.

Bash has a built-in seconds timer in the form of an internal variable named SECONDS(see: here for other internal variables)

Put SECONDS=0 before whatever you're checking the run time of. It needs to be after any user input to get a good result so if you're prompting for information, put it after the prompt(s).

Then, put this at the end of what you're checking:

if (( $SECONDS > 3600 )) ; then
    let "hours=SECONDS/3600"
    let "minutes=(SECONDS%3600)/60"
    let "seconds=(SECONDS%3600)%60"
    echo "Completed in $hours hour(s), $minutes minute(s) and $seconds second(s)" 
elif (( $SECONDS > 60 )) ; then
    let "minutes=(SECONDS%3600)/60"
    let "seconds=(SECONDS%3600)%60"
    echo "Completed in $minutes minute(s) and $seconds second(s)"
else
    echo "Completed in $SECONDS seconds"
fi

If you only want to know the time in seconds, you can simplify the above to:

echo "Completed in $SECONDS seconds"

As an example:

read -rp "What's your name? " "name"
SECONDS=0
echo "Hello, $name"
if (( $SECONDS > 3600 )) ; then
    let "hours=SECONDS/3600"
    let "minutes=(SECONDS%3600)/60"
    let "seconds=(SECONDS%3600)%60"
    echo "Completed in $hours hour(s), $minutes minute(s) and $seconds second(s)" 
elif (( $SECONDS > 60 )) ; then
    let "minutes=(SECONDS%3600)/60"
    let "seconds=(SECONDS%3600)%60"
    echo "Completed in $minutes minute(s) and $seconds second(s)"
else
    echo "Completed in $SECONDS seconds"
fi

Tags:

Bash