In bash könnten Sie tun:
echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
Beispiel:
$ ls -l | grep somefile
-rw-rw-r-- 1 me me 32 May 4 15:47 somefile
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
0 0
$ ls -l 1>/dev/null | grep while
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
0 1
Für verrohrt Vordergrundprozesse
Bei einem Skript testscript.sh sagen, das enthält:
#!/bin/bash
echo "Some Stuff"
exit 29 # Some random exit code for testing
tun
$./testscript.sh | grep somestuff
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
29 1
Für verrohrt Hintergrund
Methode 1 verarbeitet: Mit pipefail
Für testscript.sh, die enthält:
#!/bin/bash
set -eo pipefail
#set -o pipefail causes a pipeline to produce a failure return code
#If a command fails, set -e will make the whole script exit,
cat nonexistingfile # this command fails
echo "Some Stuff"
exit 29
Do
$ ./testscript.sh 2>/dev/null | grep Some &
[2] 7684
$ fg 2
bash: fg: job has terminated
[2]- Exit 1 ./testscript.sh 2> /dev/null | grep --color=auto Some
Sie erhalten den Exit-Status 1, aus dem Sie schließen, dass das Skript fehlgeschlagen ist.
Hatte cat nonexistingfile
entfernt Sie bekommen haben würde:
[2]- Done ./37257668.sh 2> /dev/null | grep --color=auto Some
Nachteilig wäre: pipefail wird wieder eine ein für alle Exit-Code, die nicht spezifisch auf den Befehl, die
fehlgeschlagen
Methode 2: Quelle das Shell-Skript
$ . ./testscript.sh 2>/dev/null | grep Some & #mind the dot in the beginning
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
29 0
Final Touch
Wenn Sie einen einzelnen Befehl zum Scheitern verurteilt in einem Shell-Skript, Testskript vermuten, könnten Sie tun unten:
#no shebang
echo "Some Stuff"
ls non_existent 2>/dev/null || ls__return_value=50
$. ./testscript | grep "Some"
$if [ $ls__return_value -eq 50 ]; then echo "Error in ls"; fi
zeigen, in welcher Weise Sie ' warten "funktioniert nicht. –