3

How to read ${PIPESTATUS[0] of a command, when a variable is set in current shell? Is there a way to pass it to current shell somehow?

I am setting variable MAIL=$(ldapsearch.... | find_for_mail) and want to be sure if ldapsearch did not failed itself before I decide that mail attribute does not really exists in LDAP.

$ true | false
$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]}
0 1
$ Z=$(true | false)
$ echo ${PIPESTATUS[0]}
1                        <--- why 1?
$ echo ${PIPESTATUS[1]}

$ Z=$(true | false;echo ${PIPESTATUS[0]} ${PIPESTATUS[1]})
$ echo $Z
0 1
$ Z=$(true | false;C="${PIPESTATUS[0]} ${PIPESTATUS[1]}")
$ echo $C

$ Z=$(true | false;export C="${PIPESTATUS[0]} ${PIPESTATUS[1]}")
$ echo $C
2

The problem is that export exports variables as environment variables from the parent to the child process, not the other way around. If you are only interested in one of the exit codes you can use this:

$ Z=$(false | true; exit ${PIPESTATUS[0]})
$ echo $?
1
1
  • Thank you, it does what I want. – Chris May 10 '19 at 9:18
0

One way to do it on Linux would be to pass the data using a temporary file (<<< happens to use a temporary file).

{
  output=$(cmd1 | cmd2 | cmd3; printf '%s\n' "${PIPESTATUS[@]}" > /dev/fd/3)
  readarray -t cmdsubst_pipe_status <&3
} 3<<< ''
printf '%s\n' "cmd1's status: ${cmdsubst_pipe_status[0]}"

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.