FIELD NOTES / UNIX & LINUXNew tools on weekdays. Beyond the man page.
$timeout

timeout: put a deadline on work without mistaking it for containment

Bound slow commands, choose an escalation policy, and preserve enough status and output to know what actually happened.

THE DEEP DIVE14 MIN READ
01

Put the first boundary around one command

GNU timeout starts another command, waits for a duration, and sends a signal if the command is still running when that duration expires. It is a standalone GNU Coreutils utility, not a Bash built-in. POSIX.1-2024 now specifies a timeout utility, but the tested GNU Coreutils 9.4 interface predates that edition and differs in option spellings and some status details; this article identifies the GNU forms it executes. Reach for timeout when waiting forever is worse than treating unfinished work as a controlled failure.

The mental model matters: timeout is a supervisor with a timer, not a speed limit or a sandbox. It starts the command named after the duration and reports how that supervision ended. By default, expiry sends TERM, a request that a process may catch or ignore.

Run the examples in order in one Bash session. They were tested with GNU Coreutils 9.4 and Bash 5.2.21 on Linux. The setup creates and enters a disposable timeout-lab directory. If that directory already exists, choose another name and rerun the whole block; the && operators stop later steps when an earlier one fails. LC_ALL=C selects stable English diagnostics for this shell and its children.

TERMINALSETUP AND COMMAND
export LC_ALL=C &&
mkdir timeout-lab &&
cd timeout-lab &&
if timeout 0.1s sleep 5; then
  printf '%s\n' 'command completed'
else
  status=$?
  printf 'timeout status: %s\n' "$status"
fi
TERMINALEXPECTED OUTPUT
timeout status: 124

0.1s is the duration: a decimal number followed by s for seconds. GNU also accepts m, h, and d for minutes, hours, and days; seconds are the default when there is no suffix. Sleep 5 is the complete command being supervised here: sleep waits for five seconds unless timeout interrupts it. In printf's format, %s inserts the following string and \n ends the line. The shell's if takes its else branch after a nonzero status. status=$? immediately saves that status before printf can replace it. Status 124 is GNU timeout's default report that the duration expired. Actual delivery can be later than the requested instant under system load, so a deadline is not a real-time guarantee. A duration of zero disables that timer; it does not mean “stop immediately.”

02

Keep child failure separate from expiry

When the child finishes before the deadline, timeout normally returns the child's status. This block runs a successful true, then a Bash process that deliberately exits with status 7. bash -c asks Bash to interpret the following quoted string as shell code; the single quotes keep exit 7 together for that child shell.

A child can itself return 124. GNU's --verbose flag writes a diagnostic to standard error for each signal timeout sends, which can provide operational evidence that expiry actually caused a signal. The 2> redirections create or replace diagnostic files. wc -c counts their bytes, and < quick.err makes that file wc's standard input; the wc deep dive explains why a byte count describes the captured stream, not its meaning.

TERMINALGNU COREUTILS AND BASH
timeout 1s true
printf 'completed status: %s\n' "$?"
timeout 1s bash -c 'exit 7'
printf 'child status: %s\n' "$?"
timeout --verbose 1s bash -c 'exit 124' 2> quick.err
quick_status=$?
printf 'quick status: %s; diagnostic bytes: ' "$quick_status"
wc -c < quick.err
timeout --verbose 0.1s sleep 5 2> timed.err
printf 'timed status: %s\n' "$?"
cat timed.err
TERMINALEXPECTED OUTPUT ON GNU 9.4
completed status: 0
child status: 7
quick status: 124; diagnostic bytes: 0
timed status: 124
timeout: sending signal TERM to command 'sleep'

The first two commands did not time out: zero belongs to true, and 7 belongs to the child shell. The quick 124 also came directly from the child and produced no timeout signal diagnostic; the timed 124 accompanied a sent TERM. A nonzero result therefore does not by itself mean the timer fired. Diagnostics are evidence from this supervisor run, not proof that cleanup finished or every descendant stopped.

03

Give TERM a cleanup path

TERM is useful precisely because a program may catch it, write state, and exit. The next synthetic worker installs a Bash trap: when TERM arrives, it writes cleanup.log and exits successfully. The while :; do ...; done loop repeats forever because : is Bash's always-successful no-op. Standard error from the managed shell is retained in term-shell.err rather than mixed into the article's stable output.

The second worker also catches TERM, but exits 42. GNU --preserve-status changes the supervisor's report on expiry: instead of the usual 124, it returns the managed command's resulting status.

TERMINALGNU COREUTILS AND BASH
timeout 0.1s bash -c 'trap "printf \"cleanup ran\\n\" > cleanup.log; exit 0" TERM; while :; do sleep 1; done' 2> term-shell.err
printf 'default timeout status: %s\n' "$?"
cat cleanup.log
timeout --preserve-status 0.1s bash -c 'trap "exit 42" TERM; while :; do sleep 1; done' 2> preserve-shell.err
printf 'preserved child status: %s\n' "$?"
TERMINALEXPECTED OUTPUT
default timeout status: 124
cleanup ran
preserved child status: 42

The first worker performed cleanup, yet the supervisor still reported expiry with 124. The second reported 42 because --preserve-status asked for the child's outcome. Preserve-status can be useful when the child's protocol matters more than identifying expiry, but it deliberately removes the distinctive 124 report. Timeout does not add a grace period merely because it sent TERM; without another option, it waits for a command that ignores or never finishes handling the signal.

04

Escalate only after a defined grace period

GNU --kill-after=DURATION, also written -k DURATION, starts a second timer when the initial signal is sent. If the command still runs when that grace period expires, timeout sends KILL. KILL cannot be caught, blocked, or used for application cleanup.

This controlled worker deliberately ignores TERM with trap "" TERM. The main deadline is 0.1 seconds; --kill-after=0.2s allows a further 0.2 seconds before KILL. The braces group the command so Bash-generated signal diagnostics are captured in kill-shell.err too.

TERMINALGNU COREUTILS AND BASH
{ timeout --kill-after=0.2s 0.1s bash -c 'trap "" TERM; while :; do sleep 1; done'; } 2> kill-shell.err
printf 'forced-stop status: %s\n' "$?"
TERMINALEXPECTED OUTPUT
forced-stop status: 137

Status 137 is 128 plus signal 9, KILL. It says that the managed command or timeout itself received KILL; GNU documents that those cases cannot be distinguished from the status alone. It does not say cleanup ran. The grace timer begins after the initial signal, so this policy allows roughly 0.3 seconds here, subject to scheduling delay. A zero main duration or zero kill-after duration disables the associated timer.

05

Choose a signal for a documented protocol

GNU --signal=SIGNAL, or -s SIGNAL, replaces the initial TERM. The argument may be a signal name or a number. Use this only when the managed program documents a useful response; changing signals does not make an arbitrary program safer.

These synthetic workers catch Linux x86-64's USR1, whose number is 10 in the tested environment, print a message, and exit with distinct statuses. --preserve-status makes those child statuses visible. The symbolic form is clearer and avoids assuming the same number on another platform.

TERMINALGNU COREUTILS, BASH, LINUX X86-64
timeout --signal=USR1 --preserve-status 0.1s bash -c 'trap "printf \"caught USR1\\n\"; exit 33" USR1; while :; do sleep 1; done' 2> usr1-shell.err
printf 'symbolic signal status: %s\n' "$?"
timeout --signal=10 --preserve-status 0.1s bash -c 'trap "printf \"caught signal 10\\n\"; exit 34" 10; while :; do sleep 1; done' 2> signal10-shell.err
printf 'numeric signal status: %s\n' "$?"
TERMINALEXPECTED OUTPUT IN THE TESTED ENVIRONMENT
caught USR1
symbolic signal status: 33
caught signal 10
numeric signal status: 34

Signal names and numbers are operating-system interfaces, not arbitrary labels. Check kill -l, which lists signal names and numbers, on the target system. Do not use KILL when you require cleanup; no trap can handle it.

06

Decide whether descendants belong to the boundary

By default, GNU timeout normally places the managed command in a separate process group and signals that group. That helps reach ordinary descendants, but it is not a promise to find every process: a program can create another session or otherwise escape the group.

GNU --foreground disables that separate background process group so an interactive command can read the controlling terminal and receive terminal-generated signals normally. The tradeoff is explicit in the GNU manual: children of the managed command are not timed out in this mode. This demonstration creates no real service. Each shell starts one child that waits 0.3 seconds and then writes a file. The outer sleep 0.4 gives any survivor time to act; [ -e FILE ] tests whether the file exists.

TERMINALGNU COREUTILS AND BASH
timeout 0.1s bash -c '(sleep 0.3; printf "%s\n" "default child survived" > default-child) & wait'
printf 'default status: %s\n' "$?"
sleep 0.4
if [ -e default-child ]; then printf '%s\n' 'default child file exists'; else printf '%s\n' 'default child stopped'; fi
timeout --foreground 0.1s bash -c '(sleep 0.3; printf "%s\n" "foreground child survived" > foreground-child) & wait'
printf 'foreground status: %s\n' "$?"
sleep 0.4
cat foreground-child
TERMINALEXPECTED OUTPUT
default status: 124
default child stopped
foreground status: 124
foreground child survived

Parentheses run the delayed writer in a subshell; & backgrounds it, and wait makes the managed shell wait for a child. Under the default grouping, the delayed child was signaled with its group. Under --foreground, the managed shell timed out but its child continued and wrote the file. Foreground mode is a terminal and job-control decision, not a recursive kill switch. For a real process tree, learn how the application forks, creates sessions, and delegates work before choosing the boundary.

07

Wrap the entire shell expression you intend

Shell operators are outside timeout unless you deliberately put them inside a child shell. The | operator connects the left command's standard output to the right command's standard input. In the next pipeline, timeout supervises only the bash -c command to the left of |. Head copies the beginning of its input, and -n 1 limits that copy to one line; the head deep dive develops that boundary further. The quoted child code prints one record and then waits.

Bash normally reports a pipeline's last command, so successful head hides the left side's 124. set -o pipefail changes Bash's pipeline status to the rightmost nonzero status, which is 124 here. set +o pipefail explicitly disables that setting for the first run.

TERMINALGNU COREUTILS AND BASH
set +o pipefail
timeout 0.1s bash -c 'printf "%s\n" "first record"; sleep 1' | head -n 1
printf 'without pipefail: %s\n' "$?"
set -o pipefail
timeout 0.1s bash -c 'printf "%s\n" "first record"; sleep 1' | head -n 1
printf 'with pipefail: %s\n' "$?"
TERMINALEXPECTED OUTPUT
first record
without pipefail: 0
first record
with pipefail: 124

Pipefail improves status propagation; it does not move head inside the timer. To supervise an entire compound expression, make that expression the explicit command, for example timeout 1s bash -c 'producer | consumer', and understand that quoting and process-group behavior now cross another shell boundary. The tee deep dive develops the related lesson that preserving a stream and preserving every pipeline status are separate problems.

08

Preserve output and environment deliberately

A leading shell assignment applies to the command that follows and is inherited by its descendants. Here MODE=audit is visible to timeout and the child Bash. The > redirection captures standard output, while 2> captures standard error. Both files are created or replaced by the current shell before timeout starts, so a command that cannot be invoked can still leave empty capture files.

TERMINALGNU COREUTILS AND BASH
MODE=audit timeout 1s bash -c 'printf "mode=%s\n" "$MODE"; printf "%s\n" "diagnostic" >&2' > command.out 2> command.err
printf '%s\n' 'stdout:'
cat command.out
printf '%s\n' 'stderr:'
cat command.err
TERMINALEXPECTED OUTPUT
stdout:
mode=audit
stderr:
diagnostic

The >&2 on the child's second printf sends that message to file descriptor 2. Capturing both streams preserves useful evidence, but those files can contain secrets and are derived records, not a guarantee of completeness. A force-killed program may have buffered data that never reached either file.

09

Classify bounded work without collapsing every failure

A reusable wrapper should save the status immediately and retain both streams before interpreting them. This Bash function accepts a short label followed by a command. label=$1 copies the first argument, and shift removes it so "$@" expands to the remaining command and arguments without merging them. : > FILE creates or empties each capture file. The braces let the outer 2>> append any Bash-generated signal diagnostic to the same error file. case compares $status with each pattern before ). In 125|126|127, the vertical bars mean alternative case patterns, not a pipeline; * matches anything not handled earlier, ;; ends an arm, and esac closes the construct. In the final printf, %s prints a string, while %-8s and %-3s left-align strings in fields eight and three characters wide, producing the shown columns.

TERMINALBASH
run_bounded() {
  label=$1
  shift
  : > "$label.out"
  : > "$label.err"
  { timeout --kill-after=0.2s 0.1s "$@" > "$label.out" 2> "$label.err"; } 2>> "$label.err"
  status=$?
  case $status in
    0) result=completed ;;
    124) result=timed-out ;;
    137) result=killed-after-grace ;;
    125|126|127) result=setup-or-invocation-failed ;;
    *) result=child-status ;;
  esac
  printf '%-8s status=%-3s result=%s\n' "$label" "$status" "$result"
}
run_bounded quick true
run_bounded child bash -c 'exit 7'
run_bounded timed sleep 5
run_bounded forced bash -c 'trap "" TERM; while :; do sleep 1; done'
run_bounded missing no-such-clitdj-command
printf '%s\n' 'missing diagnostic:'
cat missing.err
TERMINALEXPECTED OUTPUT ON GNU 9.4
quick    status=0   result=completed
child    status=7   result=child-status
timed    status=124 result=timed-out
forced   status=137 result=killed-after-grace
missing  status=127 result=setup-or-invocation-failed
missing diagnostic:
timeout: failed to run command 'no-such-clitdj-command': No such file or directory

GNU reserves 125 for failure in timeout itself, 126 when the command is found but cannot be invoked, and 127 when it cannot be found. A production wrapper should distinguish those three if remediation differs. It should also account for the 124 ambiguity shown earlier and for a child that exits 137 on its own. Classification is policy layered over evidence, not a fact recovered from one number.

10

Bound an unfamiliar operation; do not call it contained

The same pattern is useful during authorized administration or assessment: place a time budget around a supplied parser, metadata collector, or inventory probe; capture its two streams; and reject incomplete output unless both the status and the application's own completeness checks pass. This can reduce exposure to accidental hangs or denial-of-service behavior in a flaky tool.

It does not make hostile input safe. Timeout does not remove privileges, constrain memory or file writes, block the network, validate output, or reliably kill processes that leave its process group. Pair the deadline with appropriate privilege separation, resource controls, isolation, input policy, and application-specific validation. A timer answers “how long will this supervisor wait before signaling?” It does not answer “what was the command allowed to do?”

Before wrapping real work, decide what the duration means, which initial signal the application supports, whether it gets a grace period, and whether its descendants stay in the supervised process group. Decide which shell expression is actually inside the boundary, capture stdout and stderr with suitable permissions, and save the status before another command overwrites it.

Then interpret the outcome with its limits intact: 124 normally reports expiry but can be a child's own status; 137 reports KILL without proving who received it; preserve-status favors the child's protocol over an explicit timeout marker; and foreground mode can leave children running. With those choices explicit, timeout becomes a useful failure boundary rather than a comforting but inaccurate promise of containment.

Back to latest issue
HELP SHAPE THE NEXT ISSUE

What belongs in your toolbox?

Choose a command you want to know better. We start with familiar tools and work toward the less obvious ones.

READER’S CHOICE

What should we cover next?

Vote for a future deep dive, or suggest a command we missed.

One command name, up to 32 characters. Suggestions are reviewed by a person. A new article starts a fresh poll.

Loading poll…