First of all: timeout exits with error code 124 if the timeout has been reached.
Of particular interest is the handling of exit codes if commands are failing.
I am playing with various invocations of a timeout setting of 3 seconds and a sleep command of 5 seconds and vice versa.
Output | Exit code | ||
---|---|---|---|
The timeout threshold is reached. | |||
timeout 3 sleep 5 | 124 | ||
timeout 3 sh -c "sleep 5; exit 1" | 124 | ||
timeout 3 sh -c "echo something; sleep 5; exit 1" | something | 124 | Failure but part of the commands ran successfully creating output. |
timeout 3 sh -c " sleep 5; echo something; exit 1" | 124 | ||
The timeout threshold is not reached. | |||
timeout 5 sleep 3 | 0 | Success. The command finished before the timeout threshold. |
|
timeout 3 sh -c "exit 1" | 1 | Failure. The command finished before the timeout threshold but with an error. |
|
timeout 3 sh -c "echo something; exit 1" | something | 1 | Failure. The commands ran and finished before the timeout threshold but with an error. |
Here is an example that shows how a loop gets executed partially.
timeout 3 sh -c "for i in 1 2 3; do sleep 1; echo i=\$i; done" i=1 i=2 and exit code 124In this case one needs to carefully continue and understand possible consequences of a partially executed command chain and how to recover from timeout errors.
Error handling could be done this way:
case $? in 0) # all ok ;; 124) # this was a timeout ;; *) # some other error induced by the executed command(s) ;; esac
Maybe this usage is also helpful sometimes: capture only the timeout exit code.
timeout 3 sh -c "echo something; sleep 5" || { [ $? -eq 124 ] && echo TIMEOUT; } echo $? will show output of the executed command, the timeout exit code check and an exit code 0 something TIMEOUT 0Interesting to see what happens when the executed command fails. The exit code of the failed command is still available to subsequent checks.
timeout 3 sh -c "echo something; exit 1" || { [ $? -eq 124 ] && echo TIMEOUT; } echo $? will show output of the executed command(s) and the exit code of the command chain something 1
No comments:
Post a Comment