Running Commands with timeout

Su Suriya Ravichandran Updated 06 Dec 2026
15 min read ·Lesson 142 of 205

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: s for seconds (the default), m for minutes, h for hours, d for days. Fractions are allowed: 1.5, 0.5m. A duration of 0 disables 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:

  1. It starts COMMAND as its child and starts a timer.
  2. If the child exits before the timer runs out, timeout exits with the child's status.
  3. If the timer runs out first, timeout sends 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:

  • timeout runs an external program. It cannot see the shell's functions, aliases or built-in commands, because it is not a shell.
  • Unless --foreground is used, timeout places 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
StatusMeaning
the command's own statusthe command finished before the limit
124the time limit was reached and the signal was sent
125timeout itself failed (for example, an invalid duration)
126the command was found but could not be run
127the command was not found
137the 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). getopts stops 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 timeout duration, 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 case statement 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Running Commands with timeout and get answers drawn from it.

Signed-in readers only.