En bash, vous pouvez faire:
echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
Exemple:
$ 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
Pour les procédés de premier plan passepoilées
En cas d'un script qui contient testscript.sh disent:
#!/bin/bash
echo "Some Stuff"
exit 29 # Some random exit code for testing
do
$./testscript.sh | grep somestuff
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
29 1
Pour un fond sonore traite
Méthode 1: En utilisant pipefail
Pour testscript.sh qui contient:
#!/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
Vous obtenez un état de sortie 1 à partir duquel vous avez conclu que le script a échoué.
Si vous aviez été enlevé cat nonexistingfile
auriez obtenu:
[2]- Done ./37257668.sh 2> /dev/null | grep --color=auto Some
Disdvantage: pipefail retournera un pour tout le code de sortie qui est pas spécifique à la commande qui a échoué
Méthode 2: Source le script shell
$ . ./testscript.sh 2>/dev/null | grep Some & #mind the dot in the beginning
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
29 0
Final Touch
Si vous soupçonnez une seule commande à l'échec dans un script shell, script de test, vous pouvez le faire ci-dessous:
#no shebang
echo "Some Stuff"
ls non_existent 2>/dev/null || ls__return_value=50
Do
$. ./testscript | grep "Some"
$if [ $ls__return_value -eq 50 ]; then echo "Error in ls"; fi
Afficher en quoi ' wait' ne fonctionne pas. –