How to Calculate the Time Elapsed in Shell Scripts

I found a useful tip for printing out the time elapsed in shell scripts.

#!/usr/bin/env bash

SECONDS=0

# The script goes here.
sleep 2.57  # Simulate a script that takes 2.57 seconds to run.

# Calculate and print the time elapsed.
DURATION=$SECONDS
echo '======='
echo "RUN TIME: $(($DURATION / 60)) minutes and $(($DURATION % 60)) seconds"

The Bash documentation says:

SECONDS

This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment. The number of seconds at shell invocation and the current time is always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset.

I originally discovered the tip here: date - How to calculate time elapsed in bash script? - Stack Overflow

Iā€™m using it to print out the time it takes to deploy my main site.

3 Likes