获取管道后台进程的退出代码 [英] Get exit code of a piped background process
问题描述
someCommand 2>&1 | grep pattern &
如何获取someCommand
的退出状态?
PIPESTATUS
不起作用,因为它是一个后台进程.
PIPESTATUS
doesn't work because it's a background process.
I've found this link and it seems to work but only if I use it exactly that way. Simple echo
ing to the screen doesn't seem to work. I was wondering if it's possible to get the exit code without creating temporary files.
推荐答案
在bash中,您可以执行以下操作:
In bash you could do :
echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
示例:
$ 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
用于管道前台进程
如果是脚本,请说包含以下内容的testscript.sh:
In case of a script say testscript.sh which contains :
#!/bin/bash
echo "Some Stuff"
exit 29 # Some random exit code for testing
做
$./testscript.sh | grep somestuff
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
29 1
用于管道后台进程
方法1:使用pipefail
Method 1: Using pipefail
对于包含以下内容的testscript.sh:
For testscript.sh which contains :
#!/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
做
$ ./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
您将获得退出状态1,从中您可以得出结论脚本失败.
You get an the exit status 1 from which you conclude that the script failed.
如果已删除cat nonexistingfile
,您将获得:
Had cat nonexistingfile
been removed you would have got:
[2]- Done ./37257668.sh 2> /dev/null | grep --color=auto Some
缺点:pipefail将为所有退出代码返回一个非失败命令专用的退出代码
Disdvantage : pipefail will return a one for all exit code that is not specific to the command that failed
方法2:获取Shell脚本
$ . ./testscript.sh 2>/dev/null | grep Some & #mind the dot in the beginning
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
29 0
最终触摸
如果您怀疑单个命令在shell脚本(测试脚本)中失败,则可以执行以下操作:
If you suspect a single command to fail in a shell script,test script, you could do below :
#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
这篇关于获取管道后台进程的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!