kmail.at
contact

elsewhere

EnglishEN
← learning

shell · difficulty ◆◆

timeout — stop a command before it runs forever

A deadline in front of any command, in one word.

The cron job that hung at 02:00 and was still holding the lock at 09:00 — one word in front of that command would have prevented it.

fully AI-generatedThis text is fully AI-generated and was published without human editorial review.

2026-10-25 · 4 min read

$ timeout

The wrapper every script forgets

`timeout DURATION COMMAND` starts the command, waits, and sends SIGTERM if it is still alive. That is all. It exists because the failure mode it prevents is so common and so expensive: an `rsync` stuck on an NFS mount, a `curl` to a DNS-dead host, a `flock`-guarded job that never released. None of those fail — they just sit there, and the next scheduled run decides it is fine to start too.

The duration takes `s`, `m`, `h` or `d` suffixes and allows fractions: `timeout 0.2m sleep 30` is exactly 12 seconds. A duration of `0` disables the limit entirely, which is quietly useful — set `TIMEOUT=${TIMEOUT:-300}` at the top of a script and an operator can export `TIMEOUT=0` for a manual debug run without editing anything.

Exit codes are the whole contract

`timeout` returns the command's exit status unless it intervened, and the intervention codes are fixed: 124 for timed out, 125 if timeout itself failed, 126 if the command exists but cannot be executed, 127 if it was not found, 137 if SIGKILL was needed. So `if timeout 30 task; then echo ok; fi` conflates 'too slow' with 'crashed', which is exactly the distinction you need at 3 a.m.

Branch on it: `timeout 30 task; case $? in 124) echo 'timed out';; 0) echo ok;; *) echo failed;; esac`. And note the trap: in a pipeline every status but the last is discarded, so `timeout 2 slow | cat` exits 0 and lies to you. `${PIPESTATUS[0]}` in bash or a `set -o pipefail` at the top of the script is the fix.

TERM is a request; KILL is a fact

By default you send SIGTERM, and any program that traps TERM — most daemons, some database clients, anything with a shutdown handler — can ignore it. `-k 5` adds a second timer: 5 seconds after the polite signal, send SIGKILL, which nothing catches. That is why 137 shows up instead of 124 in the hard cases: 137 is just 128+9, the shell's way of saying the process died from signal 9.

`--foreground` is the other option people miss. Without it, timeout puts the command in its own process group so the signal reaches the whole tree — correct for a runaway job, wrong for an interactive program that needs your TTY or its Ctrl-C. Add `--foreground` when you wrap something that prompts you.

Example

$ timeout 2 sleep 10; echo "exit=$?"
exit=124

The smallest real demo: sleep wanted 10 seconds, got 2, and the 124 tells you it was killed for time rather than failing on its own.

$ timeout -v 1 sleep 5; echo "exit=$?"
timeout: sending signal TERM to command ‘sleep’
exit=124

Add -v while debugging a script: it prints what it sent and to whom, so you can tell 'never started' from 'started and got killed'.

$ timeout -k 1 1 bash -c 'trap "" TERM; sleep 20'; echo "exit=$?"
/usr/bin/bash: line 5: 1922678 Killed                  timeout -k 1 1 bash -c 'trap "" TERM; sleep 20'
exit=137

A TERM-ignoring process, the case that silently defeats naive wrappers. TERM at 1s did nothing, KILL landed a second later, and the shell reported 137 = 128+9.

$ timeout --preserve-status 2 sleep 10; echo "exit=$?"
exit=143

Now you see the command's own signal death instead of the 124 sentinel: 143 = 128+15. Use this when a supervisor or systemd unit needs the real status.

$ until timeout 1 bash -c '</dev/tcp/127.0.0.1/22' 2>/dev/null; do echo "waiting for sshd"; sleep 1; done; echo "sshd is up"
sshd is up

The container/CI pattern: probe a port with a 1-second deadline instead of a fixed sleep 30. If the port is closed the bash /dev/tcp connect fails instantly and the loop keeps waiting; here sshd was already listening so it fell straight through.

$ for try in 1 2 3; do timeout 5 curl -fsS https://kmail.at/ >/dev/null && { echo "ok on try $try"; break; }; echo "try $try failed"; sleep 2; done
ok on try 1

Retry loop with a deadline per attempt, which is what you actually want for a flaky API — a plain retry without timeout can block forever on attempt one.

Common flags

-k, --kill-after=DURATION
Send SIGKILL this long after the first signal. The only reliable way to stop a process that traps TERM.
-s, --signal=SIGNAL
Choose what to send first: `-s INT` for something that needs a Ctrl-C-style cleanup, `-s HUP` to make a daemon re-read config, `-s KILL` to skip negotiating.
--preserve-status
Return the command's own status instead of 124 when it times out. You get 143 for TERM and 137 for KILL rather than a single sentinel.
--foreground
Do not put the command in its own process group: it keeps the TTY and can read input, but its children stop being covered by the deadline.
-v, --verbose
Diagnose to stderr every signal it sends, including which command received it. Cheap and worth keeping in cron logs.
DURATION suffix
`30`, `30s`, `1.5m`, `2h`, `1d`; fractions allowed. `0` disables the timeout, which makes an env-var override trivial.
Exit 124 / 125 / 126 / 127 / 137
Timed out / timeout itself broke / found but not invokable / not found / killed with SIGKILL. Script off these, not off 'non-zero'.

History

A modern addition, not a Unix relic

Unlike kill, nice or sleep, `timeout` is not part of the original Unix toolbox — it is a GNU coreutils command, and its own man page still credits a single author: Pádraig Brady. Before it was packaged everywhere, the equivalent was a hand-rolled sandwich of background PID capture, `sleep`, and a `kill` in a trap. That is why the command is missing on older commercial Unices: it was never in POSIX.

Why the codes look so arbitrary

The exit codes 126 and 127 are the shell's ancient convention for 'cannot execute' and 'not found', and timeout passes them through untouched so a wrapper never disguises a typo as a timeout. 124 was picked as the out-of-band 'timed out' value precisely because nothing else claims it, and 137 is not a timeout code at all — it is the standard 128+signal encoding for a process killed by signal 9.

Fun facts

Pros & cons

pros

  • + One word in front of an existing command, no PID bookkeeping, no trap handlers to maintain.
  • + Signals the whole process group, so child processes of a runaway job die with it.
  • + Clear, documented exit codes that let a script distinguish slow from broken.

cons

  • − GNU-only in practice; BSD and macOS need coreutils installed, and Solaris/AIX boxes simply do not have it.
  • − SIGTERM is catchable, so without -k the wrapper can quietly fail to stop the exact daemons you most wanted to stop.
  • − Its status disappears inside a pipeline, which produces scripts that look guarded and are not.

Takeaways

  1. 1Wrap anything that touches the network, a lock or a mount in `timeout -k 10 N yourcommand`.
  2. 2Read 124 as 'timed out', not 'failed' — branch on it explicitly instead of `if timeout ...`.
  3. 3Always pair the base duration with `-k` so TERM-ignoring processes still die.
  4. 4Use `--preserve-status` when a supervisor needs the command's real signal status.
  5. 5Add `set -o pipefail` before trusting a timeout inside a pipeline; otherwise its exit code is discarded.

Related commands

archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →

← all learning