Bash - Elapsed time / Runtime

By xngo on June 30, 2019

The example below shows how to calculate elapsed time. This is useful if you want to measure the performance of your script.

# Start time: Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC)
T="$(date +%s)"
 
# Doing some intensive work for 2 days, 4 hours and 51 minutes.
  sleep 3s
  T=$((T-2*86400))  # Add 2 days
  T=$((T-4*3600))   # Add 4 hours
  T=$((T-51*60))    # Add 51 minutes
 
# Get total elapsed time
T="$(($(date +%s)-T))"
printf "Elapsed time[DD:HH:MM:SS]: %02d:%02d:%02d:%02d \n" \
          "$((T/86400))" \
          "$((T/3600%24))" \
          "$((T/60%60))" \
          "$((T%60))"

Output

Elapsed time[DD:HH:MM:SS]: 02:04:51:03 

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.