Sometimes it’s useful to write a bash script that do something like “Do this job, if it’s still running after XX second kill it”, how to implement this in a normal bash environment ?
Nothing simpler: Use the
timeout shell command to achieve this.
From its info page:
timeout runs the given COMMAND and kills it if it is still running after the specified time interval
Let’s see how to use it.
If you have a system recent enough you should have the command
timeout that is part of the coreutils package, for sure it’s not present on Centos 5/Rhel 5 so if you are still using these distributions or another “old” distribution, move to the second part of this article “What to do if you don’t have the timeout command”
The basic usage of this command is:
timeout [OPTION] DURATION COMMAND [ARG]
timeout will run COMMAND (with its ARG) and if it’s still alive after DURATION it will send a TERM signal to it.
OPTION could be:
-k DURATION, –kill-after=DURATION:
Ensure the monitored COMMAND is killed by also sending a `KILL’ signal, after the specified DURATION. Without this option, if the selected signal proves not to be fatal, `timeout’ does not kill the COMMAND.
-s SIGNAL, –signal=SIGNAL:
Send this SIGNAL to COMMAND on timeout, rather than the default `TERM’ signal. SIGNAL may be a name like `HUP’ or a number.
DURATION is a floating point number followed by an optional unit:
`s’ for seconds (the default)
`m’ for minutes
`h’ for hours
`d’ for days
A duration of 0 disables the associated timeout
This is a simple example that print the date, run
sleep for 10 seconds but with a timeout of 1 second and than run
date; timeout 1 sleep 10; date Wed Jun 19 23:04:31 CEST 2013 Wed Jun 19 23:04:32 CEST 2013
This simple output shows that the system “sleep” for just 1 second and not 10.
You can watch more examples in the following video:
What to do if you don’t have the timeout command
The best alternative that I’ve found at the moment is the bash script published at this link: http://www.bashcookbook.com/bashinfo/source/bash-4.0/examples/scripts/timeout3
This Bash shell script executes a command with a time-out. Upon time-out expiration SIGTERM (15) is sent to the process. If the signal
is blocked, then the subsequent SIGKILL (9) terminates it.
This should work on any Linux distribution with Bash.