brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: timeout stops a command that hangs

Linux and shell
~/tips/tip-linux-timeout

timeout -k 5 30 ./backup.sh

Stops a command after a set time, and force-kills it if it will not quit.

Some commands never come back. A mount on a dead network share, a curl to a host that does not answer, a script that waits for input that will not arrive.

Put a limit on it:

timeout -k 5 30 ./backup.sh

That runs the script and sends it SIGTERM after 30 seconds. With -k 5 it follows up with SIGKILL five seconds later if the process still refuses to go. Durations accept suffixes: 10s, 2m, 1h.

You can test the result in a script. When the time limit hits, timeout exits with status 124, which you can tell apart from the command’s own failure codes:

timeout 10 ping -c 100 example.com
echo $?

The caveat: timeout is part of GNU coreutils, so it is there on Linux but not on a stock macOS. And a process that ignores SIGTERM survives without -k.

I like it in cron jobs and backup scripts especially. A job that hangs forever blocks the next run, and then nobody notices until the backups are weeks old. With a limit, the job fails loudly instead, and you can fix a loud failure.

Further reading: timeout man page, On this site: xargs -P runs commands in parallel, no GNU parallel needed, On this site: trap EXIT cleans up your temp files, even when the script dies

More Linux and shell tips zoxide query -ls project eval "$(fzf --bash)" comm --total a.txt b.txt diff -r -x .git -x '*.log' one two printf '%s\n' a b c d e f | xargs -n1 -P3 --process-slot-var=SLOT sh -c 'echo "slot $SLOT got $0"; sleep 0.2' All Linux and shell tips (178) All topics

Link