timeout

2024-09-29

Understanding the Basics

The core function of timeout is simple: it runs a specified command and terminates it after a given time limit. If the command completes within the time limit, timeout exits successfully. If the command exceeds the limit, timeout sends a signal (typically SIGTERM, but configurable) to the process, giving it a chance to clean up before being forcibly terminated (with SIGKILL if it doesn’t exit gracefully).

The basic syntax is:

timeout [OPTIONS] DURATION COMMAND [ARGUMENTS]

Key Options and Examples

Let’s look at some common timeout options with practical examples:

1. Setting a Time Limit:

This example runs the sleep command (which pauses execution for a specified number of seconds) for 5 seconds, but timeout limits it to 2 seconds:

timeout 2s sleep 5s

The sleep command will be terminated after 2 seconds. You’ll see an output similar to:

sleep 5s received SIGTERM

2. Using Different Time Units:

You can specify the duration using different units:

timeout 1m ./my_long_running_script.sh  # 1 minute
timeout 30m top # 30 minutes
timeout 2h my_very_long_process # 2 hours

3. Ignoring Signals:

By default, timeout sends a SIGTERM signal. The -s option allows you to specify a different signal. To forcefully kill the process after the timeout without sending a SIGTERM, use -s KILL:

timeout -s KILL 10s sleep 20s

4. Defining a Signal Handling Method:

If you need more control over how the process responds to signals, you can specify how timeout should act after the time limit. Using the -k option allows you to send a kill signal (SIGKILL) after a specified period. For example the command below will give sleep 5s process 3 seconds to exit before sending SIGKILL.

timeout -k 3s 5s sleep 10s

5. Handling Command Exit Status:

The exit status of timeout reflects the outcome:

You can use this information in shell scripts to handle different scenarios:

if timeout 10s my_command; then
  echo "Command succeeded!"
else
  echo "Command timed out!"
fi

6. Output Redirection:

You can redirect the standard output and standard error streams of the command using standard redirection operators:

timeout 10s my_command > output.txt 2> error.txt

7. Preventing Signals from being sent:

The -t option stops the command from receiving SIGTERM or SIGKILL, ensuring it runs until completion. The timeout process will still end after the specified time, however. Note that the command will need to handle its own signals or you can use other methods such as pkill or kill afterwards.

timeout -t 10s my_command

These examples illustrate the versatility of the timeout command. It’s a useful tool for anyone working extensively with the Linux command line, enabling more efficient process management.