timeout From Zero: Give Any Command a Time Limit — and Stop It When the Time Is Up
A command starts running and goes silent — is it working, or has it died? timeout puts an upper bound on waiting: you don't need to know why it's stuck, only how long you'll wait at most. This guide runs every timeout command for real on GNU coreutils 9.4: the 124/125/126/127/137 exit-code table, -s signal choice, -k kill-after (3.002s measured), --preserve-status, -v, and the process-group rule — by default the whole group dies together.

Anyone who writes code has met this moment: a command starts running and then goes silent, and you cannot tell whether it is working hard or has died. You do not know whether to wait or not — kill it with Ctrl+C, and it might have finished ten seconds later. Timeout is made for exactly this moment: it puts a time limit on any command, and when the time is up it stops the command for you. This guide runs every command in it for real, on timeout from GNU coreutils 9.4: the default signal, the exit codes, changing the signal, the kill-after safety net, preserving the status, verbose mode, how durations are written, and the process-group rules, plus a few traps that are easy to fall into. The conclusion first: timeout's skill is not "killing processes" but "putting an upper bound on waiting" — you do not need to know why the command is stuck; you only need to decide how long you will wait for it at most. It is part of GNU coreutils, so it is already installed on virtually every Linux system you will ever log into — there is nothing to download and nothing to configure.
The simplest usage is timeout 1 sleep 5: give sleep 5 one second, and stop it when the second is up. Here is the measured transcript: time timeout 1 sleep 5 took real 0m1.002s, and the exit code was rc=124. One second, not a fraction more — timeout does what it says. Remember the number 124: it is timeout's own code for "timed out", meaning "the command did not exit by itself; I stopped it when the time came". The other way around, if the command finishes within the limit, timeout hands back the command's own exit code untouched: timeout 5 sleep 1 exits with rc=0, and timeout 5 false exits with rc=1. In other words, timeout only steps in when there is a timeout; when there is none, it is a transparent messenger.
Exit codes are the heart of timeout, so here is the whole table at once. The command exits normally within the limit: you get the command's own exit code. The command times out: 124. Timeout itself fails (for example, you wrote the duration wrong): 125. The command was found but cannot be executed (for example, no execute permission): 126. The command is not found at all: 127. The command was killed by the KILL signal: 137 (that is, 128 plus 9). The demo produced each of these for real: timeout xyz sleep 1 printed timeout: invalid time interval 'xyz' with exit code rc=125; timeout 1 /etc/hostname printed timeout: failed to run command '/etc/hostname': Permission denied with rc=126; timeout 1 nonexistent-cmd-xyz-285 printed timeout: failed to run command 'nonexistent-cmd-xyz-285': No such file or directory with rc=127. When you write a script, checking the exit code is the only reliable method — whether there is anything in the output, or whether an error appeared on screen, is less trustworthy than the exit code.
When the time runs out, timeout sends the TERM signal by default. TERM means "please exit by yourself": a program that receives it can clean up before leaving — close files, write logs, release locks. Most programs exit obediently on TERM, which is why timeout 1 sleep 5 exits with 124. But some programs catch TERM, ignore it, or deliberately refuse it — a service with a signal handler, or a program in the middle of a critical operation. Then TERM is not enough, and you need a harder signal. That is what -s (--signal) is for: timeout -s KILL 1 sleep 5 sends KILL directly, and KILL cannot be caught or ignored — receive it and you die. In the measured run, that command's exit code was rc=137, not 124 — a detail worth remembering: the same "timeout" reports a different exit code depending on whether you sent TERM or KILL.
Why is sending KILL 137 instead of 124? That comes down to how timeout reports the "cause of death". 124 means "it timed out, and I handled it the default way"; 137 means "the command was killed by signal 9" (128 plus 9 equals 137). When you specify -s KILL, timeout is effectively saying "count this timeout as a death by signal", so it reports the signal's cause of death. By the same logic, --preserve-status (-p) makes timeout report the command's cause of death as it was: timeout --preserve-status 1 sleep 5 exits with rc=143, which is 128 plus 15 (TERM is signal 15); timeout --preserve-status -s KILL 1 sleep 5 exits with rc=137, which is 128 plus 9. Put the numbers together and the rule is clear: without -p, a TERM timeout reports 124 and a KILL timeout reports 137; with -p, it always reports 128 plus the signal number. When your script needs to tell "did it time out, or did the command fail by itself", -p is your friend.
-k (--kill-after) is "polite first, forceful second": send one signal first (TERM by default), and if the command is still alive after the specified time, follow up with KILL. The demo measured it like this: time timeout -k 1 2 sh -c 'trap "" TERM; sleep 10' — the inner command uses trap "" TERM to ignore the TERM signal, then sleeps for 10 seconds. The timeline: at 2 seconds timeout sends TERM, and the command ignores it; one second later timeout sends KILL, and the command dies. The measured total was real 0m3.002s, with exit code rc=137. This option fits "give it a chance to clean up, but not forever" scenarios: first give TERM so the program has a chance to exit properly, and if it has not exited after the grace period, KILL as the safety net. How long the grace period should be depends on the program's temperament: databases and editors that need to write to disk deserve a few seconds; a stateless little tool needs only 1 second.
-v (--verbose) is for debugging: timeout tells you on standard error what signal it sent. In the demo, timeout -v 1 sleep 5 printed timeout: sending signal TERM to command 'sleep', then exited with rc=124. You do not need it on a normal day, but when you suspect "did timeout actually act" or "did it send the right signal", that one line is the evidence. When you are debugging a script, adding -v and looking once beats guessing for half an hour.
Timeout is forgiving about how durations are written. A number can carry a suffix: s for seconds (the default — no suffix means seconds), m for minutes, h for hours, d for days; the number can be a decimal, so timeout 0.5 sleep 2 is half a second, measured at real 0m0.502s with exit code rc=124. Writing 0 means no limit — the same as not adding timeout at all. Note that when the time comes, timeout acts, no matter what step the command has reached. So leave margin in the limit: for a test that normally takes 8 seconds, a 10-second limit is reasonable; 9 seconds is betting that it will not be a little slower today. That is especially true when you put a limit on a command an agent runs: the model's thinking time is itself unstable, so set the limit by "the slowest run", not by "the average run".
The process-group rule is the most easily misunderstood part of timeout, and the most valuable finding in this demo. By default, timeout puts the command in a new process group, and when the time runs out the signal goes to the whole group — which means background child processes started by the command are stopped together with it. The demo verified this: timeout 1 sh -c 'sleep 287 & wait', where the inner sleep 287 was started in the background; after timeout returned 124, a check found no survivor: the background sleep died with its parent — the background sleep died along with it. But --foreground is the exception: the manual states that in this mode, the command's child processes are not timed out. In the demo, after timeout --foreground 1 sh -c 'sleep 289 & wait' returned 124, the background sleep 289 was still alive; the transcript reads survivor: with --foreground the background sleep is still alive, and it was killed manually before cleanup was complete. Remember the rule: by default the whole group dies together; only --foreground spares the children.
--foreground (-f) has another side: it allows the command to read input from the terminal and receive terminal signals. The manual's own words: when timeout is not run directly from a shell prompt, adding it lets the command read the TTY and receive TTY signals. When would something be "not run directly from a shell prompt"? For example, when your command is started by another program, or runs in the background inside a script. An interactive command — one that asks you to type a password or press a confirmation key — may fail to read input or receive the Ctrl+C you press if it lacks -f. A non-interactive command does not need it. So the rule of thumb is: if the command talks to a person, add -f; if the command runs by itself and leaves, do not.
When should you use timeout? The three most common cases are these. The first is putting a limit on tests and builds: timeout 120 npm test means a hung test waits at most two minutes and never drags the whole pipeline down with it. The second is putting a limit on network requests: downloads, syncs, fetches — once the network stalls, nobody knows how long the wait will be, and timeout is the last line of defence. Note that curl has its own --max-time, but that only governs curl's waiting; timeout governs the whole command, including everything before curl starts and after it ends. The third is putting a limit on commands an agent runs: in vibe coding, if a command you asked an agent to run gets stuck, the whole session gets stuck with it; wrapping it in timeout at least guarantees it will come back within the limit. What the three cases share is that you do not need to know why the command is stuck — you only need to decide how long you will wait for it at most.
Two more traps should be written down first. The first is the ambiguity of exit code 124: 124 can mean "timeout killed the command", but it can also mean the command itself returned 124 — if your command can return 124 on its own, you cannot tell who did it. The fix is to make the command return a different code, or to use --preserve-status to state the cause of death clearly. The second is the "generation" problem of signals: by default timeout signals the process group, or the direct child process with --foreground — but if your command starts its own children and puts them in a different process group, timeout's signal cannot reach them. That shows up with containers, daemons, and double-forked programs; when debugging, look at the process tree first, then decide who the signal should go to.
Finally, the relationship between timeout and watch. The previous guide on watch covered "run every few seconds and watch for changes"; this one covers "run once and stop when the time is up". The two commands govern the two directions of time: watch is "repetition", timeout is "an upper bound". When debugging, they are often used together: first put timeout around a command that might hang, guaranteeing it will come back; then use watch to run it on a schedule and see how each return changes. The full demo transcript is in demo285_timeout_transcript.txt: the version line timeout (GNU coreutils) 9.4, finishing in time with rc=0 and the command failing by itself with rc=1, the timeout at real 0m1.002s with rc=124, changing to the KILL signal with rc=137, preserving the status with rc=143 and rc=137, the kill-after safety net at real 0m3.002s with rc=137, the verbose mode line timeout: sending signal TERM to command 'sleep', the three codes 125, 126, and 127, the half-second limit at real 0m0.502s, the two-line conclusion of the process-group rule, and the final --- done (work dir removed, no file left) ---. The work directory is deleted when done; no files are left behind.
Timeout and sleep are often compared, but they are two different tools: sleep is "wait a while", timeout is "wait at most a while". When you write sleep 5, you are telling the script to stop and wait 5 seconds; when you write timeout 5 some-command, you are telling the command it has at most 5 seconds to run. The two can be combined — timeout 10 bash -c 'sleep 2; do-work' means "the whole flow has at most 10 seconds, first wait 2 seconds inside it and then do the work". When you cannot tell them apart, ask yourself: do I want it to "wait", or do I want to "set a limit" on it? To wait, use sleep; to set a limit, use timeout.
The choice of signal is also worth expanding, because choosing the wrong signal is the most common misuse of timeout. TERM is the default, and the most polite: a program that receives it has a chance to clean up, save progress, and exit normally. HUP originally meant "the terminal hung up"; many daemons treat it as "re-read the configuration" rather than "exit" — using HUP as a "kill" signal very likely will not kill anything. INT is the signal Ctrl+C sends, and it suits interactive programs. KILL is the last resort: it cannot be caught, cannot be ignored, and leaves no chance to clean up — a file may be half-written, a lock may be left unreleased, a child process may become an orphan. So the order for choosing a signal should be: TERM first, and if that fails, add -k to fall back to KILL; only send -s KILL directly when you are sure the program ignores even TERM, and you do not care whether it cleaned up. Going straight to KILL is like pulling the power plug at the first sign of trouble — it works, but you have to accept the cost.
Using timeout in pipelines and CI needs two points of special care. First, timeout should wrap the outermost layer: timeout 120 npm test limits the whole test run, not one test command inside it. If you only limit one step, the other steps can still hang and drag the pipeline down. Second, the pipeline has to understand 124: many CI systems mark any non-zero exit code red, but 124 is not "the tests failed" — it is "it timed out" — and the log should separate the two, or you will waste half an hour investigating whether "the tests broke" or "the tests timed out". A good habit is to check explicitly in the script: timeout 120 npm test; rc=$?; if [ $rc -eq 124 ]; then echo "tests timed out"; fi. Three extra lines, half an hour saved when debugging.
Timeout can also wrap a whole pipeline and hold the entire chain. timeout 5 sh -c 'generate-data | process-data | save-data' stops the whole pipeline when the time comes, and the exit code is the pipeline's exit code. There is a detail here: timeout only recognizes the command it started directly — here that is the whole sh -c shell, not one link in the pipeline. When the signal goes to the process group, all three commands in the pipeline receive it; but with --foreground, a background link in the pipeline may escape. This is the same process-group rule as before: first work out "who will receive the signal", then decide whether to add -f.
Setting the limit to 0 means "no limit" — the same as switching timeout off. That looks useless, but there are two scenarios where it earns its keep. The first is debugging: you suspect timeout killed the command, or the command exited by itself — set the limit to 0 and run it once, and see whether the command ends on its own without any limit. The second is configuration: the script reads the limit from a variable, timeout "$LIMIT" some-command, and setting LIMIT to 0 temporarily disables the limit without changing the script's structure. Remember what 0 means; at a critical moment it can save one round of editing code.
Finally, the whole table collapses into one sentence, convenient to stick beside your monitor: if the command finishes in time, it returns its own code; if it times out, TERM reports 124 and KILL reports 137; with -p, it always reports 128 plus the signal number; timeout's own problems report 125, a missing command reports 127, and an unexecutable command reports 126; polite-first-then-forceful is -k, keep evidence with -v, talk to a person with -f, and by default the whole group dies together. Once you have that table memorized, timeout has no secrets left — all that remains is the decision of "how long the limit should be", which only you can judge.
There is one more layering problem worth flagging: many platforms already have their own timeouts, and they should not be stacked on top of timeout. A CI system has job-level timeouts, a container orchestrator has health-check timeouts, a systemd service has TimeoutStartSec, and an agent sandbox has its own limits. If there is already a timeout outside and you add another timeout inside, then when the two limits fight, which layer died and which code was reported becomes very hard to trace. The rule of thumb is: set the limit in only one layer, and set it at the layer closest to the problem — running by hand on the command line, use timeout; running in CI, use CI's own timeout; if you want both layers, make the inner limit shorter than the outer one with enough of a gap (for example, 120 seconds inside and 300 seconds outside), so the inner one acts first and the outer one is only the safety net.
Finally, the test environment, so you can compare it with your own machine. Every command in this guide was run on timeout from GNU coreutils 9.4 (the first line of timeout --version reads timeout (GNU coreutils) 9.4); the manual page is timeout(1) from man7.org, taken from the coreutils 9.11 tarball. The options and exit codes are the same in both versions, and every conclusion in this guide was verified one by one on 9.4 — including -s KILL reporting 137, --preserve-status reporting 143 and 137, -k taking 3.002 seconds, the -v message line, and the two-line conclusion of the process-group rule. On another machine or another coreutils version, the numbers should fall in the same range; if your machine reports a different exit code, check timeout --version first, then the manual — a version difference is the most common explanation.
In a script, there is a fixed pattern for using timeout that is worth copying directly. The most common is to run first and branch on the exit code: timeout 60 deploy.sh; rc=$?, then if [ $rc -eq 124 ]; then echo "deploy timed out"; elif [ $rc -ne 0 ]; then echo "deploy failed with $rc"; else echo "deploy done"; fi. The key is to store $? in a variable before checking it — because any command in between, even an echo, will overwrite $?. Another common pattern chains timeout with &&: timeout 30 fetch-data && process-data, so a timeout short-circuits and the later steps never run. A third is "retry once": the first timeout is followed by waiting a few seconds and running again, and only a second timeout counts as giving up — useful for network requests that occasionally stutter, but a waste of double the time for a command that will certainly time out. First work out which case you are in, then decide whether to retry.
One last use is directly related to vibe coding: putting a time limit on commands an agent runs. When you ask an agent to run tests, a build, or a migration, the worst outcome is not an error — it is the command getting stuck. One stuck command can drag the whole session to a timeout while you sit beside it and can only wait. Wrapping the command in timeout is buying insurance for that run: it will definitely come back by the deadline, and the exit code will tell you whether it finished or was stopped. For the agent, the exit code 124 is itself a piece of information: it says "the command was not wrong; the time ran out", and the agent can decide from that whether to retry, change approach, or report to you. How long the limit should be depends on the nature of the command: tests and builds at twice their usual time, network requests at three times their usual time, leaving room for jitter. The point of insurance is not that it is always used, but that it is always there.
It is also worth saying plainly what timeout cannot do, so you do not reach for it in the wrong place. Timeout cannot make a slow command fast; it can only stop waiting for it. It cannot tell you why a command hung — a deadlocked database, a network that never answers, a prompt waiting for input all look the same from the outside, and all of them produce the same 124. It cannot clean up after a KILL: a half-written file stays half-written, and a lock left behind stays locked until something else removes it. And it cannot protect you from a command that forks into the background and escapes its process group — the signal simply never reaches it. Knowing these limits is part of knowing the tool: timeout buys you a guaranteed return, not a diagnosis, and the diagnosis still has to come from logs, process trees, and the command's own output.
Choosing the limit itself deserves a few concrete numbers, because "how long" is the one decision timeout cannot make for you. For a test suite that normally takes 40 seconds, 120 seconds is a sensible limit: three times the usual time, enough room for a slow day, short enough that a hung run does not burn the afternoon. For a network fetch that normally takes 3 seconds, 30 seconds is reasonable: ten times the usual time, because networks are the least predictable part of any system. For a build that normally takes 4 minutes, 10 minutes is a good limit: two and a half times the usual time, with room for a cold cache. The pattern is the same in each case — take the usual time, multiply by two or three, and round up to a round number. A limit that is too tight fires on ordinary slow days and teaches everyone to ignore it; a limit that is too loose is barely a limit at all. And when you genuinely do not know how long a command takes, run it once without a limit and time it first — then set the limit from the measurement, not from a guess.
Scope note: this guide covers only timeout (GNU coreutils 9.4, the timeout(1) manual) — giving a command a time limit, sending a signal when it expires, and reporting the exit code. Its boundaries with previously published guides are as follows: the watch guide covers running a command repeatedly on a schedule, not a single time limit; the ps guide covers a process snapshot at one moment, not sending signals; the signal numbers themselves are mentioned here only as needed, not developed separately; the sleep command appears here only as the example being timed, not as a separate subject. Curl's --max-time is mentioned here only as a comparison, not developed.

Comments (0)
Sources
Related articles
df answers one question: how much space is left on each file system. This guide runs every command for real on GNU coreutils df 9.4 — a 100M file moving Use% from 2% to 21%, inodes with df -i, and the classic trap: a deleted-but-open file keeps its space until the process exits — with output pasted verbatim.
ss reads the kernel's socket table: who is listening, what state each connection is in, which process holds the socket. This guide runs every command for real on iproute2 ss 6.1.0 — a live http.server on 127.0.0.1:18080, LISTEN vs ESTABLISHED, state filters, ss -s, Unix sockets — with output pasted verbatim.
Your service died, or it did not come back after a reboot. systemctl is the remote control for systemd: start, stop, status, and boot persistence. This guide runs every command for real on systemd 255: read-only inspection, a transient scope, a real service written from scratch, started, enabled, stopped, and deleted — plus the measured finding that is-active returns 4, not 3, when a unit is gone entirely.