Domanda

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?

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top