How to set a "timeout" for commands 

http://www.oase-shareware.org/shell/scripts/quickies/timeout

Sometimes it is desirable to set a "timeout" for a command. If it does not complete within a certain period of time, it should be terminated automatically, and the script should continue.

The following example shows how to terminate a program ("ping 127.0.0.1") automatically if it does not finish execution within five seconds:

timeout=5                       # in seconds
ping 127.0.0.1 & cmdpid=$!      # Command to terminate
# Start "watchdog" process to terminate the command
# after $timeout seconds:
(sleep $timeout; kill -9 $cmdpid) &
watchdogpid=$!
wait $cmdpid                    # wait for command
kill $watchdogpid >/dev/null 2>&1

The example script starts a "timed" command in the background ("ping 127.0.0.1"), and then starts another background process (the "watchdog") that will terminate the command in 5 seconds.

It then waits for the "ping" command to terminate. If it terminates in time, the "watchdog" is terminated immediately, and the script continues.

If the command does not terminate in time, the "watchdog" process will "kill" it after the timeout period, and the script will continue. The subsequent termination of the "watchdog" will not be necessary (but will do no harm, either).

A more generic "timeout" script to monitor any arbitrary programs is available at the SHELLdorado "Scripts" section: