I discovered the timeout
command while testing Redis connectivity in a cron job. A Redis server was unreachable, and the redis-cli
command would hang indefinitely. By adding a timeout flag, I ensured the command would exit after a few seconds, avoiding unnecessary delays in the cron task.
Here’s what it looked like:
timeout 5 redis-cli -h unreachable-server ping || echo "Server is unreachable"
In this example:
- The
redis-cli
command is given 5 seconds to respond. - If it doesn’t, the
timeout
command kills it, and theecho
command logs the failure.
The timeout command is part of the GNU Coreutils package, which comes pre-installed on most Debian-based systems. If it’s missing, you can install it with:
sudo apt update
sudo apt install coreutils
The syntax is straightforward:
timeout [DURATION] [COMMAND]
- DURATION: Time limit (e.g., 5s for 5 seconds, 1m for 1 minute, 1h for 1 hour).
- COMMAND: The command you want to run.
Useful examples
- Limit a command to 10 seconds:
timeout 10s curl http://example.com
- Test a server’s reachability with
ping
:
timeout 3s ping unreachable-server
- Chain commands with a timeout:
timeout 2m some-command && echo "Command completed" || echo "Timeout reached"
- Force kill after timeout:
Add —signal=SIGKILL to ensure the command is terminated forcefully after the timeout:
timeout --signal=SIGKILL 5s some-long-running-command