11

I'm using the timeout function on debian to wait 5 seconds for my script. Works great but the problem I have is that I need a return value. Like 1 for timeout and 0 for no timeout How am I going to do this?

Have a look at my code:

timeout 5 /some/local/script/connect_script -x 'status' > output.txt
# here i need the return of timeout

As you see my connect_script -x 'status' returns the status as a string and print it to the screen (probably you can't see this) Background of this issue is that if the server (for connect_script) is freeze the script does nothing. That's why I need the timeout around that. And when it timeouts I want to restart the server. I can do that, but I have no idea how I can see if its timeout or not...

21

If timeout times out, it exits with status 124; you can check this to determine whether the script timed out or not.

| improve this answer | |
  • Yeah thanks. I miss this in the manual. @Christopher post an answer that works for me. I don't know the $? syntax. So both of your answers are right ;) – Zero May 22 '15 at 14:55
7

According the manual (man timeout):

Synopsis timeout [OPTION] NUMBER[SUFFIX] COMMAND [ARG]...

[...] If the command times out, then exit with status 124. Otherwise, exit with the status of COMMAND

Combine this with the knowledge that the exit status or return value is stored in the variable, $?, and we have...

timeout 5 /some/local/script/connect_script -x 'status' > output.txt
RETVAL=$?

Then, you can do more processing based on the value of $RETVAL, which will be 124 if it times out, or some other value based on the exit status of connect_script.

| improve this answer | |
1

The return value of timeout depends on the signal you use to terminate the child.

SIGTERM returns 124:

timeout -s SIGTERM 1 sleep 2; echo $?

But SIGKILL returns 137:

timeout -s SIGKILL 1 sleep 2; echo $?

See the manual page:

If the command times out, and --preserve-status is not set, then exit with status 124. Otherwise, exit with the status of COMMAND. If no signal is specified, send the TERM signal upon timeout. The TERM signal kills any process that does not block or catch that signal. It may be necessary to use the KILL (9) signal, since this signal cannot be caught, in which case the exit status is 128+9 rather than 124.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.