How to Run a Command with Time Limit (Timeout) In Linux

Run Linux Commands Using the timeout Tool

Linux has a command-line utility called a timeout, which enables you to execute a command with a time limit.

Its syntax is as follows.

timeout [OPTION] DURATION COMMAND [ARG]...
# timeout 5s ping google.com

You do not have to specify the (s) after number 5. The command below is the same and will still work.

# timeout 5 ping google.com

Timeout Ping Command in Linux

Other suffixes include:

  • m representing minutes
  • h representing hours
  • d representing days

Sometimes commands may continue to run even after timeout sends the initial signal. In such instances, you can use the --kill-after option.

Here’s the syntax.

-k, --kill-after=DURATION

You need to specify a duration to let timeout know after how much time the kill signal is to be sent.

For example, the command shown is going to be terminated after 8 seconds.

# timeout 8s tail -f /var/log/syslog

Set Time Limit to Linux Commands

Run Linux Commands Using Timelimit Program

The Timelimit program runs a given command then terminates the process after a specified time using a given signal. It initially passes a warning signal, and then after a timeout, it sends the kill signal.

Unlike the timeout option, Timelimit has more options such as killsigwarnsigkilltime, and warntime.

Timelimit can be found in the repositories of Debian-based systems and to install it, use the following command.

$ sudo apt install timelimit

For Arch-based systems, you can install it using AUR helper programs e.g., Pacaur Pacman, and Packer.

# Pacman -S timelimit
# pacaur -S timelimit
# packer -S timelimit

Other Linux distributions, you can download timelimit source and manually install it.

After installation, run the following command and specify the time. In this example, you can use 10 seconds.

$ timelimit -t10 tail -f /var/log/pacman.log

Note that if you don’t specify arguments, Timelimit uses the default values: warntime=3600 seconds, warnsig=15killtime=120, and killsig=9.

Conclusion

In this guide, you have learned how to run commands with a time limit in Linux. In review, you can use the Timeout command or the Timelimit utility.

The Timeout command is easy to use, but the Timelimit utility is a bit complicated but has more options. You can choose the most suitable option depending on your needs.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *