Linux commands
Browse topics

Limiting how long a command runs with timeout

Version
unversioned
Review
Draft

Summary#

timeout runs a command and signals it if it is still running after the given duration.

Syntax#

sh
timeout 30s ./slow-job
timeout -s INT 2m ./slow-job
timeout -k 5s 30s ./slow-job
timeout --preserve-status 30s ./slow-job

Durations accept s, m, h or d; seconds are the default. -s chooses the signal and -k sends KILL if the command survives that much longer. The exit status is 124 when the limit is reached, unless --preserve-status asks for the command's own status.

Example#

sh
(
  set -u
  timeout 5 true
  echo "finished in time: $?"
  timeout 0.2 sleep 5
  echo "limit reached: $?"
  timeout -k 0.3 0.3 sh -c 'trap "" TERM; sleep 5'
  echo "ignored TERM, then killed: $?"
)

Expected output#

Text
finished in time: 0
limit reached: 124
ignored TERM, then killed: 137

Common mistakes#

A command that traps or ignores TERM keeps running, so add -k to guarantee an end. Status 137 means the process received KILL; the same status can come from the kernel's out-of-memory killer. When -s KILL is the first signal, GNU timeout reports 137, while the Rust Coreutils on Ubuntu 26.04 reports 124. timeout runs programs, not shell functions or builtins, so wrap those in sh -c. With set -e, handle status 124 explicitly or the script exits.

Version applicability#

This entry describes timeout from GNU Coreutils 9.10, with differences in Rust Coreutils 0.10 noted above. macOS does not include it without installing Coreutils.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0