brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: the SECONDS variable tells a bash script how long it has been running

Bash
~/tips/tip-bash-seconds-script-duration

SECONDS=0

Times a script or one step of it in bash without calling date.

If you want a backup script to log how long it took, you don’t need date +%s twice and some arithmetic. Bash keeps a stopwatch running for you in the variable SECONDS.

Every time you read SECONDS, it gives the number of seconds since the shell started. The nice part: you can set it yourself, and from then on it counts from that value. So set it to 0 right before the part you want to time:

SECONDS=0
rsync -a /mnt/user/appdata/ /mnt/user/backup/appdata/
duration=$SECONDS
echo "backup took $((duration / 60))m $((duration % 60))s"

You can reset it as often as you like in one script, so timing each step of a longer job is just a SECONDS=0 before every step. It also works in an interactive shell, where echo $SECONDS tells you how long that terminal has been open.

Two caveats. The resolution is one second, so a step that takes half a second shows up as 0 or 1. For finer timing, bash 5.0 and newer has EPOCHREALTIME, the current time with microseconds. And don’t unset SECONDS: the manual says it loses its special behaviour then, even if you set it again afterwards, so it becomes a plain variable that never counts.

Further reading: bash(1) manual page, Bash NEWS (new features per version)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link