Skip to content
Home
BASH - terminate command after timeout

This script will allow a command to be run with a timeout, if it has not completed within the timeout passed to the command the process will be killed.

Usage:

./cmdtimeout "ssh server2 /usr/sbin/command_that_may_hang" 5

 

Will then SSH into server 2, run the command_that_may_hang and timeout after 5 seconds if it has not completed.

vim cmdtimeout
#!/bin/bash
command=$1
# run $command in background, sleep for our timeout then kill the process if it is running
$command &
pid=$!
echo "sleep $2; kill $pid" | at now
wait $pid &> /dev/null
if [ $? -eq 143 ]; then
echo "WARNING - command was terminated - timeout of $2 secs reached."
echo
fi

 

Comments
Add New
+/-
Write comment
Name:
Email:
 
Title:
 
Please input the anti-spam code that you can read in the image.
Peter Burkholder  - Nice!   |2009-06-22 19:11:40
I needed this for a start on a cronjob that was causing me headaches. I've
tweaked a bit so I don't need the 'at now' call. See
...

http://typo.pburkholder.com/2009/06/22/bash-c ommand-timeout
christian  - dont use at   |2009-07-22 07:48:02
Hi,

nice little script, but it is not so good to use "at now", because
it is possible that a normal user is not allowed to use it (on the Cluster i
work, it is :-(
So use:

eval "sleep ; kill $pid" &
andrea  - Alternative way   |2009-09-22 11:07:55
not a EshPERT. A much simpler method that worked for me:

sleep timeout &&
command&
command{ ,&} # w/ or w/o trailing "&", if you have time to wait
or not
andrea  - errata   |2009-09-22 13:14:44
simpler method that worked for me:

sleep timeout && killall command&

command{
,&} # w/ or w/o trailing "&"
 

Main Menu

Home

Login Form






Lost Password?
No account yet? Register

JoomlaWatch

JoomlaWatch Stats 1.2.6 by Matej Koval