Run command with time limit in Linux
In Linux, some commands take a long time to run, and we wait for the complete command but for some commands, we terminate that command using the kill command after some time. What if we automate the termination of long-running commands after some time. Yes, we can do it in Linux. There are two ways we can limit the time for the command, one is the timeout command and another is using the timelimit program.
Linux has a timeout command-line utility by using this utility we can kill the command if it is not completed within the time limit. Now let’s see the syntax of the timeout command
timeout [OPTION] DURATION COMMAND [ARG]...
Here in the place of duration mention time second or minute or hours by using the number followed by:
- s for second
- m for minutes
- h for hours
If you do not mention any character from above after the number, the timeout will consider as a second. And after that, mention the command for which we have to limit the time.
Now let’s take one example we are going to ping command with 5s:
timeout 5s ping google.com
Then you can see that the command is terminated after the 5sec.
If we do not mention the s after 5 then the command will run as before.
We can also set the single to send after the killing process using the single option -s or –signal. Here is example
timeout --signal=SIGQUIT 8 tail -f /var/log/pacman.log
Some commands may continue to execute even after sending the initial signal we can handle this type of command using the -k or –kill option with time. Following is syntax
To know more about the timeout command, use the man command:
The timelimit is a utility that executes a given command with a given time limit. If the mentioned command is terminated before mentioned time, then the timelimit silently exit. Before killing the command, the timelimit sends a warning to the command and then sends a kill signal.timelimit provides more options than the timeout command which is very useful.
For Debian based systems like Ubuntu, use the following command:
sudo apt install timelimit
For arch Linux or arch-based OS, install using AUR. Use the following command:
git clone https://aur.archlinux.org/timelimit.git && cd timelimit && makepkg -sri
The basic syntax to use the timelimit is as follows:
timelimit [-pq] [-S killsig] [-s warnsig] [-T killtime] [-t warntime] command [arguments …]
The default values of the timelimit options are as follows:
- warntime(-t) : 3600
- warnsig(-s) : 15
- killsig(-S): 9
Here is one example of the timelimit command:
To know more about the timelimit command, read the man page of timelimit using man command:
Please Login to comment...