gpt4 book ai didi

bash - 当管道中的一个进程失败时退出

转载 作者:行者123 更新时间:2023-11-29 08:46:02 25 4
gpt4 key购买 nike

目标是制作一个简单的非侵入式包装器,将标准输入和标准输出跟踪到标准错误:

#!/bin/bash

tee /dev/stderr | ./script.sh | tee /dev/stderr

exit ${PIPESTATUS[1]}

测试脚本script.sh:

#!/bin/bash

echo asd
sleep 1
exit 4

但是当脚本退出时,它不会终止包装器。可能的解决方案是从管道的第二个命令结束第一个 tee:

#!/bin/bash

# Second subshell will get the PID of the first one through the pipe.
# It will be able to kill the whole script by killing the first subshell.

# Create a temporary named pipe (it's safe, conflicts will throw an error).
pipe=$(mktemp -u)
if ! mkfifo $pipe; then
echo "ERROR: debug tracing pipe creation failed." >&2
exit 1
fi

# Attach it to file descriptor 3.
exec 3<>$pipe

# Unlink the named pipe.
rm $pipe

(echo $BASHPID >&3; tee /dev/stderr) | (./script.sh; r=$?; kill $(head -n1 <&3); exit $r) | tee /dev/stderr

exit ${PIPESTATUS[1]}

那是很多代码。还有别的办法吗?

最佳答案

我认为您正在寻找 pipefail 选项。来自 bash 手册页:

pipefail

If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.

所以如果你开始你的包装脚本

#!/bin/bash

set -e
set -o pipefail

然后包装器将在发生任何错误时退出 (set -e) 并将以您想要的方式设置管道的状态。

关于bash - 当管道中的一个进程失败时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com