O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

timeout

The read and select commands honor the variable TMOUT, which defines the maximum number of seconds they should wait for interactive input. Other commands do not have this functionality built in, but it can be an essential feature, particularly for scripted operations. This simple script is useful for demonstrating just what timeout does because it does not always do exactly what you might expect.

download.eps
cat longcmd.sh
#!/bin/bash
trap 'echo "'date': ouch!"' 15
echo "'date': Starting"
sleep 20
echo "'date': Stage Two"
sleep 20
echo "'date': Finished"

longcmd.sh

On the first run, -s 15 3 tells timeout to send a SIGTERM (signal 15) to the script after 3 seconds. This is trapped by the script, but it has the effect of killing the first sleep command. So, 3 seconds after starting, at 13:33:46, the ouch! message is displayed as the script handles the trap. Execution resumes with the next command in the script, which echoes the date (still 13:33:46), sleeps for 20 seconds, and finishes at 13:34:06.

timeout -s 15 3 ./longcmd.sh ; date
Thu Mar 24 13:33:43 GMT 2011: Starting
Terminated
Thu Mar 24 13:33:46 GMT 2011: ouch!
Thu Mar 24 13:33:46 GMT 2011: Stage Two
Thu Mar 24 13:34:06 GMT 2011: Finished
Thu Mar 24 13:34:06 GMT 2011
warning.ai

GNU coreutils did not have a timeout tool until version ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required