3 # Author: P@draigBrady.com
6 # Execute a command with a timeout.
7 # If the timeout occurs the exit status is 128
9 # Note there is an asynchronous equivalent of this
10 # script packaged with bash (under /usr/share/doc/ in my distro),
11 # which I only noticed after writing this.
13 if [ "$#" -lt "2" ]; then
14 echo "Usage: `basename $0` timeout_in_seconds command" >&2
15 echo "Example: `basename $0` 2 sleep 3 || echo timeout" >&2
21 kill %1 2>/dev
/null
#kill sleep $timeout if running
22 kill %2 2>/dev
/null
&& exit 128 #kill monitored job if running
25 set -m #enable job control
26 trap "cleanup" 17 #cleanup after timeout or command
27 timeout
=$1 && shift #first param is timeout in seconds
28 sleep $timeout& #start the timeout