Reputation: 1947
I want to run a script with the timeout
command and exit 0
if the script runs with no problem or the timeout occurs. Otherwise, if the script exits with some non-0
code, I want to preserve that.
My imaginary syntax would be that timeout
implements something like --exit
so I can write timeout --exit 0 10s ping google.com
.
I have seen this other answer on SO, which says you can handle the exit code of timeout
with an or
condition, like timeout 10s ping google.com || [[ $? -eq 143 ]]
. But that is hard coding the result of timeout
, and if my script fails and throws a 143
, it will fail silently. I also don't want to force exit 0. If the script fails I want to know.
I am looking for an answer that preserves all failures (and non-failures) from the script, but always exits 0 from timeout
. If there is a workaround that doesn't use timeout
with a low cognitive complexity I will consider that as well.
Upvotes: 1
Views: 1492
Reputation: 302
Run the timeout
command, and save its exit code to a variable. Compare that against 124, which is the code when the command times out. If the code was 124, we'll exit with 0 to convert the failing exit code into success. If the exit code was not 124, we have the original command's status because timeout
exits with that when the command ran to completion.
timeout 10s COMMAND
status="$?"
if (( status == 124 )); then
# Command timed out
exit 0
fi
# Command either succeeded or failed
exit "$status"
The one gotcha is when the original command exits with 124 as timeout
will propagate that exit code too. To this code, it will look like the command timed out so it will exit with 0 when it should be exiting with nonzero as the original command failed. There is no (easy) way to differentiate the two situations.
Upvotes: 4