Running Commands with timeout
Some commands can run much longer than expected. A network request waits for a server that never answers, a mounted network drive stops responding, or a test hangs because of a bug. In an interactive terminal you notice and press Ctrl + C, but a script running from cron or in a CI pipeline has nobody watching it. One hung command can block the whole script, and the next scheduled run may start while the first is still stuck.
timeout puts an upper limit on how long a command may run. It starts the command, and if the command has not finished when the time is up, timeout sends it a signal. The script then continues, and the exit status tells it what happened.
timeout is not part of Bash. It is a separate program from GNU coreutils, installed on practically every Linux system. On systems without GNU coreutils, such as a default macOS installation, it may be missing; the Homebrew coreutils package provides it (installed as gtimeout unless its gnubin folder is placed first in PATH). The examples in this lesson were run with GNU coreutils 9.4 and Bash 5.2.
The Basic Form
timeout [OPTIONS] DURATION COMMAND [ARG]...
- DURATION is a number with an optional unit:
sfor seconds (the default),mfor minutes,hfor hours,dfor days. Fractions are allowed:1.5,0.5m. A duration of0disables the limit. - COMMAND and its arguments follow exactly as they would without
timeout.
TIMEFORMAT='took %1Rs'
time timeout 2 sleep 5; echo "status $?"
time timeout 2 sleep 1; echo "status $?"
took 2.0s
status 124
took 1.0s
status 0
The first sleep would have needed 5 seconds; timeout stopped it after 2 and returned status 124, its special value for "the time limit was reached". The second sleep finished in time, and timeout passed its exit status through unchanged.
How timeout Works
timeout is a small supervisor process:
- It starts COMMAND as its child and starts a timer.
- If the child exits before the timer runs out,
timeoutexits with the child's status. - If the timer runs out first,
timeoutsends the child a signal, by default SIGTERM, waits for it to end, and exits with status 124.
Two details shape everything else in this lesson:
timeoutruns an external program. It cannot see the shell's functions, aliases or built-in commands, because it is not a shell.- Unless
--foregroundis used,timeoutplaces itself and the command in a new process group, and sends the signal to the whole group. Programs started by the command are therefore stopped too.
Exit Status
The exit status of timeout combines two sources: its own results and those of the command.
timeout 2 false; echo "false: status $?"
timeout 2 ls /nope; echo "ls: status $?"
timeout abc sleep 1; echo "bad duration: $?"
timeout 2 nosuchcmd; echo "missing: $?"
timeout 2 ./notexec.txt; echo "not executable: $?"
false: status 1
ls: cannot access '/nope': No such file or directory
ls: status 2
timeout: invalid time interval 'abc'
Try 'timeout --help' for more information.
bad duration: 125
timeout: failed to run command 'nosuchcmd': No such file or directory
missing: 127
timeout: failed to run command './notexec.txt': Permission denied
not executable: 126
| Status | Meaning |
|---|---|
| the command's own status | the command finished before the limit |
| 124 | the time limit was reached and the signal was sent |
| 125 | timeout itself failed (for example, an invalid duration) |
| 126 | the command was found but could not be run |
| 127 | the command was not found |
| 137 | the command (and timeout) were ended by SIGKILL (128 + 9) |
The statuses 126 and 127 follow the shell's own conventions (lesson 116), so a script can treat them the same way with or without timeout.
These values can overlap with the command's own statuses. A command that exits with 124 by itself looks exactly like a timeout:
timeout 2 bash -c 'exit 124'; echo "command itself exited 124: $?"
command itself exited 124: 124
In practice few programs use 124 or 125, but a script that wraps a program with unusual exit codes should keep this in mind.
Choosing the Signal
-s SIGNAL (or --signal=SIGNAL) sends a different signal when the time is up. The status is still 124, except with SIGKILL:
timeout -s INT 1 sleep 5; echo "INT: $?"
timeout -s KILL 1 sleep 5; echo "KILL: $?"
INT: 124
a.sh: line 12: 740 Killed timeout -s KILL 1 sleep 5
KILL: 137
With SIGKILL, the signal goes to the whole process group, which includes timeout itself. timeout is killed together with the command and cannot report 124, so the shell sees 137 and prints a Killed message.
SIGINT is useful for programs that treat Ctrl + C as "stop and print what you have so far"; SIGTERM, the default, is the right choice for most commands.
Keeping the Command's Own Status
--preserve-status makes timeout exit with the command's status even after a timeout. A command ended by the signal then reports 128 plus the signal number:
timeout --preserve-status 1 sleep 5; echo "preserve: $?"
timeout --preserve-status -s INT 1 sleep 5; echo "preserve INT: $?"
preserve: 143
preserve INT: 130
This option is meant for commands that handle the signal and exit with a meaningful status of their own. For most scripts, the plain 124 is easier to check.
Seeing What timeout Does
-v (--verbose) prints a message on standard error when the signal is sent:
timeout -v 1 sleep 5; echo "verbose: $?"
timeout: sending signal TERM to command 'sleep'
verbose: 124
Commands That Ignore SIGTERM: -k
A program may handle SIGTERM and keep running, or ignore it completely. timeout then waits for it indefinitely, and the time limit has no effect. This script handles SIGTERM by printing a message and carrying on:
# stubborn.sh
trap 'echo "stubborn: ignoring TERM"' TERM
for i in 1 2 3 4 5 6 7 8 9 10; do sleep 0.5; done
echo "stubborn: finished normally"
TIMEFORMAT='took %1Rs'
time timeout 1 bash stubborn.sh; echo "no -k: status $?"
time timeout -k 1 1 bash stubborn.sh; echo "with -k 1: status $?"
Terminated
stubborn: ignoring TERM
stubborn: finished normally
took 5.0s
no -k: status 124
Terminated
stubborn: ignoring TERM
b.sh: line 3: 768 Killed timeout -k 1 1 bash stubborn.sh
took 2.0s
with -k 1: status 137
Without -k, the script ran for its full 5 seconds even though the limit was 1 second. The Terminated line shows the process-group behavior: the sleep 0.5 inside the script also received SIGTERM, and the script's Bash reported that its foreground sleep had been terminated. The script itself survived, because of its trap.
-k DURATION (--kill-after=DURATION) adds a second deadline: if the command is still running DURATION after the first signal, timeout sends SIGKILL, which cannot be handled. With -k 1, the script was killed after 1 + 1 = 2 seconds, and the status was 137.
timeout -k 5 LIMIT command is a good default for scripts: the command gets a polite SIGTERM and 5 seconds to clean up, and is forced to stop only if it does not.
Functions, Built-ins and Pipelines
Because timeout runs external programs, a shell function or a built-in command cannot be passed to it directly:
f() { sleep 3; }
timeout 1 f; echo "function: $?"
timeout 1 cd /; echo "builtin cd: $?"
timeout: failed to run command 'f': No such file or directory
function: 127
timeout: failed to run command 'cd': No such file or directory
builtin cd: 127
To limit shell code, run a new Bash under timeout. A function must be exported with export -f to be visible there:
export -f f
time timeout 1 bash -c f; echo "bash -c f: $?"
took 1.0s
bash -c f: 124
The same applies to pipelines and loops. In timeout 1 sleep 3 | sleep 2, the limit applies only to the first command of the pipeline; the pipeline as a whole still takes 2 seconds, and its status is that of the last command:
time { timeout 1 sleep 3 | sleep 2; }; echo "PIPESTATUS: ${PIPESTATUS[*]}"
time timeout 1 bash -c 'sleep 3 | sleep 2'; echo "whole pipeline limited: $?"
time timeout 2 bash -c 'for f in a b c; do echo "step $f"; sleep 1; done'; echo "status $?"
took 2.0s
PIPESTATUS: 124 0
took 1.0s
whole pipeline limited: 124
step a
step b
took 2.0s
status 124
When the whole pipeline or loop runs in bash -c, the limit covers all of it. The loop was stopped during its third step. Use single quotes around the bash -c code so that the outer shell does not expand variables in it first (lesson 46).
Child Processes Are Stopped Too
Because the signal goes to the process group, programs started by the command are stopped as well:
timeout 1 bash -c 'sleep 4 & wait'; echo "grandchild bash: $?"; sleep 0.2
echo "sleep left after group kill: $(pgrep -xc sleep -r S,R)"
timeout --foreground 1 bash -c 'sleep 4 & wait'; echo "--foreground: $?"; sleep 0.2
echo "sleep left after --foreground: $(pgrep -xc sleep -r S,R)"
grandchild bash: 124
sleep left after group kill: 0
--foreground: 124
sleep left after --foreground: 1
With --foreground, timeout stays in the caller's process group and signals only the command itself. The inner bash ended, but the sleep it had started kept running. (pgrep -r S,R counts only running and sleeping processes.)
timeout, the Terminal and Ctrl + C
The new process group has a side effect when timeout is used inside a script that runs in a terminal. Typed directly at the prompt, timeout behaves like any other command; the interactive shell makes it the foreground job, and Ctrl + C stops it:
$ timeout 5 sleep 30
^C
$ echo "status $?"
status 130
Inside a script, timeout moves itself out of the script's process group, and the terminal sends Ctrl + C only to the foreground process group (lesson 141). This script was interrupted half a second after it started:
# ctrlc.sh
echo "ctrlc.sh: running timeout 5 sleep 30"
timeout 5 sleep 30
echo "ctrlc.sh: timeout returned $?"
$ bash ctrlc.sh
ctrlc.sh: running timeout 5 sleep 30
^Cctrlc.sh: timeout returned 124
$ echo "status $?"
status 0
Ctrl + C reached the script but not timeout or sleep. The script, as Bash does, waited for its foreground command; timeout ended sleep only when its own 5 seconds were up, and the script then carried on as if nothing had happened.
The same applies to reading from the terminal. A command that timeout has moved into a background process group is not allowed to read the terminal:
# ask.sh
timeout 5 bash -c 'read -p "name? " n; echo "hi $n"'
echo "ask.sh: status $?"
$ bash ask.sh
name? ana
exit
ask.sh: status 124
$ ana
bash: ana: command not found
The prompt appeared, but read was stopped as soon as it tried to read. The text typed by the user, ana and exit, stayed in the terminal's input buffer, timeout gave up after 5 seconds, and the interactive shell later read ana as a command.
--foreground solves both problems. timeout then stays in the foreground group, so the command can read the terminal and Ctrl + C reaches it:
# askfg.sh
timeout --foreground 5 bash -c 'read -p "name? " n; echo "hi $n"'
echo "askfg.sh: status $?"
$ bash askfg.sh
name? ana
hi ana
askfg.sh: status 0
The price is the one shown above: with --foreground, programs started by the command are not stopped when the time runs out. Use --foreground for interactive commands in scripts run from a terminal, and the default mode for unattended scripts.
For the specific case of waiting for user input, the built-in read -t SECONDS (lesson 31) is simpler: read -t 5 -p "name? " n gives up after 5 seconds with a status above 128, without any external program.
A Complete Example: Retrying with a Time Limit
Commands that talk to the network often fail temporarily. A common pattern is to give each attempt a time limit, retry a few times, and wait a little longer after each failure. retry.sh packages this pattern:
#!/usr/bin/env bash
# retry.sh [-t LIMIT] [-n TRIES] [-d DELAY] COMMAND [ARG]...
# Run COMMAND with a time limit per attempt. Retry after a failure or a
# timeout, doubling the pause between attempts. Exit with the last status.
set -uo pipefail
prog=${0##*/}
limit=10 tries=3 delay=1
usage() {
echo "usage: $prog [-t LIMIT] [-n TRIES] [-d DELAY] COMMAND [ARG]..." >&2
exit 2
}
while getopts ':t:n:d:' opt; do
case $opt in
t) limit=$OPTARG ;;
n) tries=$OPTARG ;;
d) delay=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# > 0 )) || usage
[[ $limit =~ ^[0-9]+(\.[0-9]+)?[smhd]?$ ]] || { echo "$prog: -t: invalid time limit: $limit" >&2; exit 2; }
[[ $tries =~ ^[1-9][0-9]*$ ]] || { echo "$prog: -n: need a whole number of at least 1" >&2; exit 2; }
[[ $delay =~ ^[0-9]+$ ]] || { echo "$prog: -d: need whole seconds" >&2; exit 2; }
for (( attempt = 1; attempt <= tries; attempt++ )); do
start=${EPOCHREALTIME/./}
timeout -k 5 "$limit" "$@" # SIGTERM at LIMIT, SIGKILL 5 seconds later
rc=$?
took=$(( (${EPOCHREALTIME/./} - start) / 100000 )) # tenths of a second
took="$(( took / 10 )).$(( took % 10 ))s"
case $rc in
0) echo "$prog: attempt $attempt/$tries succeeded in $took" >&2; exit 0 ;;
124) why="timed out after $took" ;;
137) why="ignored SIGTERM and was killed after $took" ;;
125|126|127) echo "$prog: could not run $1 (status $rc)" >&2; exit "$rc" ;;
*) why="failed with status $rc after $took" ;;
esac
echo "$prog: attempt $attempt/$tries $why" >&2
if (( attempt < tries )); then
echo "$prog: waiting ${delay}s before the next attempt" >&2
sleep "$delay"
delay=$(( delay * 2 ))
fi
done
echo "$prog: giving up" >&2
exit "$rc"
How It Works
- Options are read with
getopts(lesson 130).getoptsstops at the first argument that is not an option, so everything from COMMAND onwards, including the command's own options, is passed on untouched with"$@". - Validation checks the values before anything runs: the time limit must look like a
timeoutduration, the number of tries must be at least 1, and the delay must be whole seconds because it is doubled with integer arithmetic. - Each attempt runs
timeout -k 5 "$limit" "$@". The command gets SIGTERM at the limit and SIGKILL 5 seconds later if it ignores SIGTERM. - Timing uses
EPOCHREALTIME(Bash 5.0 and later), the current time in seconds with microseconds. Removing the dot gives an integer number of microseconds, and dividing the difference by 100000 gives tenths of a second. - The
casestatement turns the status into a reason. 125, 126 and 127 mean the command could not be run at all, so retrying would not help and the script stops at once with that status. - Backoff: the pause doubles after each failed attempt (1, 2, 4 seconds...), which gives a struggling service time to recover.
- Messages go to standard error, so the command's own output on standard output can still be captured or piped.
Running the Complete Example
A test command, flaky.sh, simulates an unreliable service. It counts its calls in a file: the first call hangs, the second fails, and the third works.
# flaky.sh COUNTER_FILE: hangs on the 1st call, fails on the 2nd, works on the 3rd
n=$(( $(cat "$1" 2>/dev/null || echo 0) + 1 ))
echo "$n" > "$1"
case $n in
1) echo "flaky: call 1, hanging"; sleep 30 ;;
2) echo "flaky: call 2, failing"; exit 1 ;;
*) echo "flaky: call $n, working"; sleep 0.3; echo "flaky: done" ;;
esac
With a 2-second limit and up to 4 attempts:
rm -f count; bash retry.sh -t 2 -n 4 -d 1 bash flaky.sh count; echo "status $?"
flaky: call 1, hanging
retry.sh: attempt 1/4 timed out after 2.0s
retry.sh: waiting 1s before the next attempt
flaky: call 2, failing
retry.sh: attempt 2/4 failed with status 1 after 0.0s
retry.sh: waiting 2s before the next attempt
flaky: call 3, working
flaky: done
retry.sh: attempt 3/4 succeeded in 0.3s
status 0
The hanging first call was stopped after 2 seconds instead of 30. With only 2 attempts, the script gives up and returns the status of the last attempt:
flaky: call 1, hanging
retry.sh: attempt 1/2 timed out after 1.0s
retry.sh: waiting 1s before the next attempt
flaky: call 2, failing
retry.sh: attempt 2/2 failed with status 1 after 0.0s
retry.sh: giving up
status 1
A command that ignores SIGTERM completely is ended by the -k 5 SIGKILL:
# deaf.sh: ignores SIGTERM completely (sleep inherits the ignored signal)
trap '' TERM
sleep 20
retry.sh: line 46: 994 Killed timeout -k 5 "$limit" "$@"
retry.sh: attempt 1/1 ignored SIGTERM and was killed after 6.0s
retry.sh: giving up
status 137
That took 1 second for the limit plus 5 seconds of grace. The Killed line is printed by the Bash running retry.sh, because SIGKILL ended timeout itself.
Commands that cannot be run, and invalid options, stop the script immediately:
bash retry.sh -t 1 nosuchcmd; echo "status $?"
bash retry.sh -t 1x true; echo "status $?"
bash retry.sh -n 0 true; echo "status $?"
bash retry.sh -x true; echo "status $?"
bash retry.sh; echo "status $?"
timeout: failed to run command 'nosuchcmd': No such file or directory
retry.sh: could not run nosuchcmd (status 127)
status 127
retry.sh: -t: invalid time limit: 1x
status 2
retry.sh: -n: need a whole number of at least 1
status 2
usage: retry.sh [-t LIMIT] [-n TRIES] [-d DELAY] COMMAND [ARG]...
status 2
usage: retry.sh [-t LIMIT] [-n TRIES] [-d DELAY] COMMAND [ARG]...
status 2
In a real script, the command would be something like bash retry.sh -t 20 -n 5 curl -fsS https://example.com/health: five attempts of at most 20 seconds each, with pauses of 1, 2, 4 and 8 seconds between them.