bash return code after reading for pipe bash return code after reading for pipe unix unix

bash return code after reading for pipe


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/bashreturn_code() { return $1; }    # A dummy function to set $? to any valuefifo=myPipemkfifo "${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    }