Search code examples
bashshellunixpipeexit-code

bash return code after reading for pipe


How to return $code as the exit code for this script and not the exit code of the last command rm "${fifo}".

#!/bin/bash

fifo=myPipe
mkfifo "${fifo}"|| exit 1
{
    read code <${fifo}
} | {
    timeout 1 sleep 2
    timeoutCode=$?
    echo "${timeoutCode}" >${fifo}
}
rm "${fifo}"

Solution

  • Perhaps this can serve your purpose:

    This answer has 2 parts, which you were looking for:

    1. Set $? to any required value
    2. Use ${PIPESTATUS[@]} array to obtain exit status of individual stages of the pipeline...

    Code:

    #!/bin/bash
    
    return_code() { return $1; }    # A dummy function to set $? to any value
    
    fifo=myPipe
    mkfifo "${fifo}"|| exit 1
    {
        read code <${fifo}
        return_code $code
    } | {
        timeout 1 sleep 2
        timeoutCode=$?
        echo "${timeoutCode}" >${fifo}
    }
    ret=${PIPESTATUS[0]}
    rm "${fifo}"
    exit $ret
    

    Considering that the expected exit code of the entire script is actually being generated via stage 2 of the pipeline, below logic would also work.

    #!/bin/bash
    
        fifo=myPipe
        trap "rm $fifo" EXIT #Put your cleanup here...
    
        mkfifo "${fifo}"|| exit 1
        {
            read code <${fifo}
        } | {
            timeout 1 sleep 2
            timeoutCode=$?
            echo unused > ${fifo}
            exit $timeoutCode
        }