Search code examples
bashunixtimeout

I can not get "exit status" with "timeout comand"


I expect to get "status 124", but got "status 0" with the following code

timeout 10 sleep 20 | tee -a LOG_FILE LOG_FILE2
RET=$?
echo $RET

I got "status 0" by use this code.

I expect to get "status 124".

What's happen in this code


Solution

  • $? holds the exit status of the last pipeline. Use PIPESTATUS to get the exit status of foreground pipelines (in this case the timeout command).

    $ timeout 10 sleep 20 | tee -a LOG_FILE LOG_FILE2
    $ RET=${PIPESTATUS[0]}
    $ echo $RET
    
    124  # timed out
    

    man bash

    PIPESTATUS: An array variable (see Arrays below) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).