bash time limit on commands

Several programs, like “timelimit” and “timeout”, exist to prevent a process from running for too long.
However, if you want to do this on a box where neither is installed, there’s a way to do so with bash alone.

Based on the original script I found at pixelbeat.org…

#!/bin/sh

# Execute a command with a timeout

# Author:
# http://www.pixelbeat.org/
# Notes:
# If the timeout occurs the exit status is 128.
# There is an asynchronous (and buggy) equivalent of this
# script packaged with bash (under /usr/share/doc/ in my distro),
# which I only noticed after writing this.
# I noticed later again that there is a C equivalent of this packaged
# with satan by Wietse Venema, and copied to forensics by Dan Farmer.
# Changes:
# V1.0, Nov 3 2006, Initial release
# V1.1, Nov 20 2007, Brad Greenlee
# Make more portable by using the 'CHLD'
# signal spec rather than 17.

if [ "$#" -lt "2" ]; then
echo "Usage: `basename $0` timeout_in_seconds command" >&2
echo "Example: `basename $0` 2 sleep 3 || echo timeout" >&2
exit 1
fi

cleanup() {
{ kill %1 2>/dev/null; }& # kill sleep $timeout if running
kill %2 2>/dev/null && exit 128 # kill monitored job if running
}

set -m # enable job control
trap "cleanup" CHLD # cleanup after timeout or command
timeout=$1 && shift # first param is timeout in seconds
sleep $timeout& # start the timeout
"$@" # start the job

I made a new script in bash, which also returns the correct exit status if the command completed before the timeout: timeout.bash

Works well for me, at least 🙂

1 Comment

  • sysadmin says:

    Nice. I’ve missed timeout util in centos 5, but fixed this by backporting from coreutils-8.4. If someone will need an appropriate rpm package with timeout utility for centos 5, just write me here about it.

Leave a Reply

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