Skip to content
shellmap

Run a command every N seconds

Repeat a command on a fixed-interval polling loop — useful for live dashboards, healthcheck-watching, and tail-style log monitoring.

How to run a command every n seconds in each shell

Bashunix
watch -n 5 'df -h'
Zshunix
watch -n 5 'df -h'
Fishunix
watch -n 5 'df -h'
PowerShellwindows
while ($true) { Clear-Host; df -h; Start-Sleep -Seconds 5 }

pwsh has no `watch`-equivalent cmdlet. `Clear-Host` (alias `clear` / `cls`) wipes the terminal before each iteration. `Start-Sleep` takes `-Seconds` or `-Milliseconds`. Combine with `try/finally` to cleanly exit on Ctrl-C if you need to run cleanup.

cmd.exewindows
for /l %i in (1,0,1) do @(cls & dir & timeout /t 5 /nobreak >nul)

cmd has no `watch`. `for /l %i in (1,0,1) do …` is an infinite loop (start=1, step=0, end=1 — never exits). In a `.bat` file double the percent: `%%i`. `timeout /t 5 /nobreak` waits 5 sec; `>nul` suppresses the countdown display.

Equivalents listed for Bash, Zsh, Fish, PowerShell, cmd.exe.

Gotchas & notes

  • `watch -n 5 CMD` clears the screen and reruns every 5s. Linux util-linux has it; macOS BSD does NOT (`brew install watch` from `procps-ng`). Useful flags: `-d` highlight differences between iterations, `-c` enable color output (most CMDs strip color when piped — `watch -c "command --color=always"` to keep it), `-x` use `exec` (so `watch -x sh -c "cmd | grep foo"` works without args getting mangled).
  • Portable shell loop without `watch`: `while true; do clear; date; sleep 5; done`. Add `&& break` or check an exit-flag to stop cleanly. Inside a script: `while true; do command || break; sleep $INTERVAL; done` exits the loop the moment `command` fails — better than letting a slow-failing healthcheck poll forever.
  • Sub-second polling: `watch -n 0.5 cmd` (GNU watch supports decimal); pwsh `Start-Sleep -Milliseconds 500`; bash `sleep 0.5` works on Linux + macOS BSD `sleep` (BSD `sleep` since FreeBSD 8 / macOS 10.6 accepts decimals). For very high-frequency polling (sub-100ms), use a language with real timers (Python `time.sleep`, Go `time.Tick`) — shell loop overhead dominates.
  • For exponential-backoff polling: `delay=1; while ! check-condition; do sleep $delay; delay=$((delay*2)); [ $delay -gt 60 ] && delay=60; done`. Caps at 60s to avoid runaway. Common pattern when waiting for a slow service to come up — first probe immediately, then 1s, 2s, 4s, 8s, …, 60s, 60s, …

Related commands

Related tasks