timeout and sleep: Bounding Commands That Might Hang
A script that hangs is harder to debug than one that fails, because nothing in the log says what it was waiting for. timeout is the cheapest fix available and almost nobody uses it.
timeout
timeout 30 curl -s https://example.com
timeout 5m rsync -a /data/ remote:/backup/
timeout 1h ./long-job.sh
Suffixes: s seconds and the default, m minutes, h hours, d days.
# in a script, checking what happened
if timeout 30 curl -sf https://example.com/health > /dev/null; then
echo "healthy"
else
rc=$?
if (( rc == 124 )); then
echo "timed out" >&2
else
echo "failed with $rc" >&2
fi
exit 1
fi
124 means the timeout fired. That is the whole reason to check the code rather than just the success or failure, because a timeout and a 500 response are different problems.
| Code | Meaning |
|---|---|
| 124 | Time limit reached |
| 125 | timeout itself failed |
| 126 | Command found but not executable |
| 127 | Command not found |
| 137 | Killed by SIGKILL, so 128+9 |
| other | The command’s own exit code |
Our exit codes guide covers the 128+signal convention.
SIGTERM, then SIGKILL
The part that matters for anything touching data.
# default: SIGTERM, which asks politely
timeout 30 ./job.sh
# SIGTERM, then SIGKILL 10 seconds later if it is still there
timeout -k 10 30 ./job.sh
# a different signal
timeout -s SIGINT 30 ./job.sh
timeout -s SIGQUIT 30 ./job.sh
-k is the one to use for real work. timeout 30 alone sends SIGTERM and gives up; if the process ignores it, you have a timeout that did not time anything out.
Do not send SIGKILL as the first signal. SIGKILL cannot be caught, so a database mid-write, a tar mid-archive or an rsync mid-transfer is left in whatever state it was in. SIGTERM gives it a chance to clean up, and -k is the enforcement if it will not.
Our process signals guide covers which signals can be caught, and our trap guide covers handling SIGTERM in your own scripts so the clean shutdown actually happens.
# a script that cooperates with timeout
#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp)
cleanup() { rm -f "$tmp"; }
trap cleanup EXIT TERM INT
# ... work ...
Pipelines and process groups
# this does not do what it looks like
timeout 10 cat bigfile | grep pattern
# wrap it
timeout 10 bash -c 'cat bigfile | grep pattern'
# and to signal the whole group
timeout --foreground -k 5 10 bash -c './a.sh | ./b.sh'
timeout runs one command. In the first form it bounds cat and not the pipeline.
--foreground is needed when the command must read from the terminal, or when you want signals to reach the whole process group rather than just the direct child. Without it, timeout puts the child in its own group, which is usually right and occasionally not.
sleep
sleep 5
sleep 0.5 # GNU, not POSIX
sleep 2m
sleep 1h30m
Decimals and suffixes are GNU extensions. BusyBox and minimal systems may accept only whole seconds, which matters for a script running in an Alpine container.
# portable
sleep 1
The drift problem
# this does not run every 60 seconds
while true; do
do_work # takes 5 seconds
sleep 60
done
# actual interval: 65 seconds
Each iteration costs the work plus the sleep. Over a day that is a drift of hours.
# compensate
while true; do
start=$(date +%s)
do_work
elapsed=$(( $(date +%s) - start ))
(( elapsed < 60 )) && sleep $(( 60 - elapsed ))
done
Better: do not write this loop at all. A systemd timer handles scheduling properly, restarts after a crash, logs to the journal, and survives a reboot:
# /etc/systemd/system/myjob.timer
[Timer]
OnCalendar=*:0/1
AccuracySec=1s
Persistent=true
Our cron versus timers guide covers the choice, and a while true; sleep loop in a service file is the thing both replace.
Do not sleep to wait for something
The most common misuse.
# wrong
docker compose up -d
sleep 10
curl http://localhost:8080/health
Ten seconds is too long when the service starts in two and too short when the machine is loaded. The failure is intermittent, which is the worst kind.
# right: poll for the condition, with a bound
wait_for() {
local timeout=${2:-60} elapsed=0
until eval "$1"; do
(( elapsed >= timeout )) && return 1
sleep 0.5
elapsed=$(( elapsed + 1 ))
done
}
docker compose up -d
if wait_for 'curl -sf http://localhost:8080/health >/dev/null' 60; then
echo "ready"
else
echo "did not become ready in 60s" >&2
docker compose logs
exit 1
fi
This succeeds as soon as the condition is true and fails with a useful message if it never is.
# purpose-built tools for the common cases
timeout 60 bash -c 'until nc -z localhost 5432; do sleep 0.5; done'
# or
wait-for-it.sh localhost:5432 -t 60
Our netcat guide covers nc -z for port checks, and our open ports guide covers the alternatives.
For systemd, express the dependency rather than polling:
[Unit]
After=postgresql.service
Requires=postgresql.service
And for a service that genuinely needs to signal readiness, Type=notify with sd_notify is the correct mechanism, per our service files guide.
Timeouts elsewhere
Worth knowing, because the tool usually has its own and it is better than wrapping.
# curl
curl --max-time 30 --connect-timeout 5 https://example.com
# ssh
ssh -o ConnectTimeout=10 -o ServerAliveInterval=15 -o ServerAliveCountMax=3 host
# wget
wget --timeout=30 --tries=3 https://example.com
# the shell's own read
read -t 5 -p "answer within 5s: " answer || echo "no answer"
ssh with ConnectTimeout only is a common half-measure: it bounds the connection, not a session that hangs after connecting. ServerAliveInterval and ServerAliveCountMax are what detect a dead link mid-session, which matters for the scripts in our rsync guide.
# in ~/.ssh/config, so every connection gets it
Host *
ConnectTimeout 10
ServerAliveInterval 15
ServerAliveCountMax 3
In systemd units
[Service]
TimeoutStartSec=120
TimeoutStopSec=30
RuntimeMaxSec=1h
# for a oneshot job that must not run forever
Type=oneshot
TimeoutStartSec=30m
TimeoutStopSec is the one people hit. It is how long systemd waits after SIGTERM before sending SIGKILL during shutdown, and the default is why a reboot occasionally sits on “A stop job is running” for 90 seconds.
# which unit is holding up shutdown
systemd-analyze blame | head
journalctl -b -1 | grep -i 'stop job'
RuntimeMaxSec bounds a service’s total runtime, which is the unit-file equivalent of timeout for something that should never run for hours.
A pattern worth copying
#!/usr/bin/env bash
set -euo pipefail
readonly LOCK=/var/lock/myjob.lock
readonly MAX_RUNTIME=3600
exec 9>"$LOCK"
flock -n 9 || { echo "already running" >&2; exit 0; }
cleanup() { rm -f "${tmp:-}"; }
trap cleanup EXIT
tmp=$(mktemp)
if ! timeout -k 30 "$MAX_RUNTIME" ./actual-work.sh > "$tmp" 2>&1; then
rc=$?
if (( rc == 124 )); then
printf 'timed out after %ds\n' "$MAX_RUNTIME" >&2
fi
cat "$tmp" >&2
exit "$rc"
fi
A lock so it cannot overlap, a timeout with a kill grace period, a trap for cleanup, output captured so a failure is reportable. Our flock and mktemp guide covers the locking and our bash error handling guide covers the rest.
Frequently Asked Questions
What signal does timeout send and can I change it?
SIGTERM by default, which asks the process to exit cleanly. Change it with -s, and use -k to send SIGKILL after an additional grace period if the process ignores the first signal. Sending SIGKILL immediately risks leaving work half done.
What exit code does timeout return when it kills something?
124 when the time limit was reached, which is how you distinguish a timeout from the command itself failing. It returns 125 for its own errors, 126 if the command could not be run, 127 if it was not found, and 137 if it was killed by SIGKILL.
Why does sleep in a loop drift over time?
Because the loop body takes time too, so each iteration costs the sleep plus the work. Over hundreds of iterations that accumulates. For anything that must happen on a schedule, use a systemd timer or compute the remaining time rather than sleeping a fixed interval.
How do I wait for a service to be ready instead of sleeping?
Poll for the condition in a loop with a short sleep and an overall timeout. Sleeping a fixed ten seconds is both too long when the service starts fast and too short when it does not, whereas polling for the port or the health endpoint succeeds as soon as it is true.
Can sleep handle fractional seconds?
GNU sleep accepts decimals and suffixes for minutes, hours and days, so sleep 0.5 and sleep 2m both work. That is not POSIX, so a script that must run on minimal systems or BusyBox should stick to whole seconds.
Does timeout work on a pipeline?
Not directly, because it runs one command. Wrap the pipeline in a shell invocation so timeout has a single process to manage, and be aware that it signals that shell rather than every member of the pipeline unless you also use the foreground and kill options.