I am using the PIPESTATUS variable to access all the exit codes of the pipeline: echo "hello" | wc -w
. Now since the commands run with success, the PIPESTATUS array returns me 0 0 when I access using echo ${PIPESTATUS[*]}
immediately after running the pipeline either in script or terminal.
However, when I try to print them separately by using the following codes:
echo "${PIPESTATUS[0]}" # it prints the output 0
echo "${PIPESTATUS[1]}" # doesn't print anything, blank terminal
The whole code is:
#!/bin/bash
echo "hello" | wc -w
echo "${PIPESTATUS[0]}"
echo "${PIPESTATUS[1]}"
how to solve this? And why it's not possible to access elements in such a way. It's an array so it should be possible. Does the PIPESTATUS have anything to do with being volatile or something?
This is what the manual says:
PIPESTATUS
An array variable containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).
The contents of PIPESTATUS
change after every pipeline. echo "${PIPESTATUS[0]}"
is a pipeline too, so PIPESTATUS
is populated with its exit status before echo "${PIPESTATUS[1]}"
is executed. But since the previous pipeline contains only one command, PIPESTATUS[1]
is rendered empty, hence the empty output.
You're looking for something like this:
echo "hello" | wc -w
status=("${PIPESTATUS[@]}")
echo "${status[0]}"
echo "${status[1]}"