Shell – Return status of Busybox `timeout` command

alpine-linuxbusyboxcoreutilsshelltimeout

I'm writing a shell script that's supposed to function on various different distributions, some of which are using busybox and some are not.

This script uses the timeout command to figure whether a command it executed ran longer than <time> or not. In the case of distributions which use the coreutils timeout this is no problem because when timeout had to kill a command it always returns 124, so that's simple.

My problem is that when I run the same on Alpine Linux (which uses busybox ) then the exit status is 0 after timeout had to kill the command, but when I use the timeout command from the busybox package in Ubuntu it exits with 143.

Why do the two timeout commands, which are both from busybox, give me a different return value?

Is there any consistency or rule in that which I can use to determine whether the command has timed out or not?

Best Answer

Alpine Linux probably has an earlier version of busybox. A simple solution is to add to your original command another command that has some side effect you can test for, eg writing some output to stdout or a file.

Eg, assuming you want a timeout of 1 for an original command of sleep 2, instead of

timeout 1 sleep 2

do

ok=$(timeout 1 bash -c 'sleep 2; echo ok')

and test $ok for ok. Obviously, if your command writes to stdout you need to redirect it, eg dup it to fd 3 and redirect to that:

exec 3>&1
ok=$(timeout 1 bash -c 'my command >&3; echo ok')
exec 3>&-

or do the echo ok into a file.

Related Question