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.

cat longcmd.sh
trap 'echo "'date': ouch!"' 15
echo "'date': Starting"
sleep 20
echo "'date': Stage Two"
sleep 20
echo "'date': Finished"


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
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

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

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.