Bash: using timeout to put time limit on invoked commands

When calling processes within a script, there may be situations where you need to put a time limit on the call due to significant blocking times.  Perhaps a DNS or network call would block if certain firewall rules do not exist yet, or a long-running API call would need to be considered in error if it takes longer than 15 seconds.

This can be handled using the ‘timeout‘ command, which allows you to control how many seconds a process is allowed to run before halting.  The example below shows a 5 second timeout exiting normally versus being halted early.

echo "--- 5 sec timeout not reached, normal exit code returned ---"
timeout 5 sleep 1
echo "exited uninterrupted short sleep with $? (expected 0)"

echo "---  5 sec timeout reached, timeout will stop it ---" 
timeout 5 sleep 10 
echo "exited interrupted long sleep with $? (expected 124)"

The exact exit codes returned can be found on the timeout man page (124=cmd timed out, 127=cmd not found, 137=cmd killed).

Here is another example using ping, which would continue forever except for the fact that we put a 3 second timeout in place.

echo "---ping will die after 3 seconds ---"
timeout 3 ping 127.0.0.1
echo "exited ping with $? (expected 124 for timeout)"

Here is the full source to test_timeout.sh

REFERENCES

man timeout