문제

in bash i am trying to make a script that goes:

echo hi | while read line; do echo $line; done

&

echo $?

would return 0


lets say the first script messed up somehow:

ech hi | while read line; do echo $line; done

&

echo $?

would still return 0

How does one go about returning that error?

도움이 되었습니까?

해결책

The Bash internal variable $PIPESTATUS does this. It is an array containing the exit status(es) of the commands in the last executed pipe. The first command in the pipe is $PIPESTATUS[0], etc:

$ ech hi | while read line; do echo $line; done
-bash: ech: command not found
$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]}
127 0

$ echo hi | while read line; do ech $line; done
-bash: ech: command not found
$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]}
0 127

$ echo hi | while read line; do echo $line; done
hi
$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]}
0 0
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top