从命名管道捕获非零退出代码

dar*_*ber 2 bash exit-code named-pipes

tmp.sh即使发送到命名管道的进程失败,以下玩具脚本()也会以代码0退出.如何从命名管道捕获非零退出代码?或者更一般地说,事情出了问题?

#!/bin/bash

set -eo pipefail

mkfifo mypipe
FOOBAR > mypipe &

cat mypipe
Run Code Online (Sandbox Code Playgroud)

运行并检查退出代码:

bash tmp.sh
tmp.sh: line 6: FOOBAR: command not found

echo $? # <- Exit code is 0 despite the "command not found"!
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 5

您需要捕获后台进程的进程ID并wait为其设置正确的退出状态:

#!/bin/bash
set -eo pipefail

rm -f mypipe
mkfifo mypipe

FOOBAR > mypipe &
# store process id of above process into pid
pid=$!

cat mypipe

# wait for background process to complete
wait $pid
Run Code Online (Sandbox Code Playgroud)

现在当你运行它:

bash tmp.sh
tmp.sh: line 6: FOOBAR: command not found
echo $?
127
Run Code Online (Sandbox Code Playgroud)