Skip to content

How to add a timeout to any Linux command

Updated: at 06:39 AM

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 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]

Useful examples

  1. Limit a command to 10 seconds:
timeout 10s curl http://example.com
  1. Test a server’s reachability with ping:
timeout 3s ping unreachable-server
  1. Chain commands with a timeout:
timeout 2m some-command && echo "Command completed" || echo "Timeout reached"
  1. 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