I composed a piped command and tried to run it under timeout
. In case the last piped command succeeds but the first does not, the status is 0 (since the last command succeed).
I read this post about getting the status using PIPESTATUS
: Pipe output and capture exit status in Bash (It also suggests using set -o pipefail
but it also does not work). However, when I try to run it under timeout the PIPESTATUS[0]
is incorrect, this might be due to the fact I need to run the piped command using bash -c
when running it under timeout
(the next post explains why timeout <time> bash -c <command>
syntax should be used Why does `timeout` not work with pipes?)
A code example:
function func {
HELLO="hello"
DOES_NOT_EXIST="does_not_exist.txt"
CMD="ls $DOES_NOT_EXIST | echo $HELLO"
echo $CMD
timeout 5 bash -c "$CMD"
echo ${PIPESTATUS[0]}
}
#main
func
output:
ls does_not_exist.txt | echo hello
hello
ls: cannot access does_not_exist.txt: No such file or directory
0
The last line is the status of echo hello
and not ls
's failure status (should be 2 if I am not mistaken). Is there a way to get the status of the first command in the pipe? (My actual need is to get the status of the first piped command no matter whether it failed or not)