timeout - Linux


Overview

The timeout command in Linux is used to run a specific command with a time limit, after which the command is terminated if it has not completed. This tool is especially useful in scripts and automation processes where a hanging or long-running process needs to be limited to prevent system resource exhaustion or to maintain performance.

Syntax

The basic syntax of the timeout command is as follows:

timeout [OPTIONS] DURATION COMMAND [ARGUMENTS...]
  • DURATION must be a positive integer followed by an optional suffix (s, m, h, d for seconds, minutes, hours, days respectively). If no suffix is provided, seconds are assumed.
  • COMMAND is the command that timeout will execute.
  • ARGUMENTS are the optional arguments passed to the command being executed.

Options/Flags

  • -k, –kill-after=DURATION: Ensures that the process is killed after a specified delay DURATION if it has not terminated after the initial period.
  • –preserve-status: Exit with the same status as the managed command, rather than overriding it with the timeout signal status.
  • -s, –signal=SIGNAL: Use this signal instead of the default SIGTERM to terminate the command. SIGNAL can be a signal name like SIGKILL or a signal number.
  • –foreground: When used, timeout does not create a new session if the command is the leader of a group, allowing signals like Ctrl+C to affect both the timeout and the commanded process.
  • -v, –verbose: Display information about the operation being conducted.

Examples

  1. Basic Usage: Terminate a command after 30 seconds:

    timeout 30 ./your_script.sh
    
  2. Complex Usage with Signal: Kill a script after 1 minute using SIGKILL:

    timeout --signal=SIGKILL 1m ./intensive_script.sh
    
  3. Use of Kill After: Terminate a command after 2 minutes, but wait for an additional 30 seconds before forcibly killing the process if still running:

    timeout --kill-after=30s 2m ./long_process.sh
    

Common Issues

  • Incorrect Duration Format: Users often forget the correct format for duration or miss the suffix. Ensure the duration is a positive integer followed by an optional time suffix.
  • Command Not Terminating with SIGTERM: Some processes may ignore the SIGTERM signal. Using -s SIGKILL can forcefully terminate these stubborn processes.

Integration

timeout can be combined with other commands to build robust scripts. For example, ensure a database dump operation does not overrun:

timeout 3600 mysqldump -u user -p database > backup.sql
  • sleep: Delays for a specified amount of time.
  • watch: Executes a command repeatedly, displaying output.
  • kill: Sends a specific signal to a specified process.

For more advanced documentation, consult the timeout man page (man timeout) or visit the GNU Coreutils page for detailed usage and examples.