PIPESTATUS(bash) + pipefail(ksh)

本文介绍了三种在Unix/Linux环境中通过管道连接多个进程时,获取上游进程退出状态的方法:使用pipefail选项、利用PIPESTATUS数组及分开执行命令并捕获状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have two processes foo and bar, connected with a pipe:

$ foo | bar

bar always exits 0; I'm interested in the exit code of foo. Is there any way to get at it?

--

There are 3 common ways of doing this:

Pipefail

The first way is to set the pipefail option (kshzsh or bash). This is the simplest and what it does is basically set the exit status $? to the exit code of the last program to exit non-zero (or zero if all exited successfully).

$ false | true; echo $?
0
$ set -o pipefail
$ false | true; echo $?
1

$PIPESTATUS

Bash also has an array variable called $PIPESTATUS ($pipestatus in zsh) which contains the exit status of all the programs in the last pipeline.

$ true | true; echo "${PIPESTATUS[@]}"
0 0
$ false | true; echo "${PIPESTATUS[@]}"
1 0
$ false | true; echo "${PIPESTATUS[0]}"
1
$ true | false; echo "${PIPESTATUS[@]}"
0 1

You can use the 3rd command example to get the specific value in the pipeline that you need.

Separate executions

This is the most unwieldy of the solutions. Run each command separately and capture the status

$ OUTPUT="$(echo foo)"
$ STATUS_ECHO="$?"
$ printf '%s' "$OUTPUT" | grep -iq "bar"
$ STATUS_GREP="$?"
$ echo "$STATUS_ECHO $STATUS_GREP"
0 1

转载于:https://www.cnblogs.com/kakaisgood/p/7681905.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值