即使发送到命名管道的进程失败,下面的玩具脚本(tmp.sh
)也会退出代码0。如何从命名管道中捕获非零退出代码?或者更笼统地说,出了什么问题?
#!/bin/bash
set -eo pipefail
mkfifo mypipe
FOOBAR > mypipe &
cat mypipe
运行并检查退出代码:
bash tmp.sh
tmp.sh: line 6: FOOBAR: command not found
echo $? # <- Exit code is 0 despite the "command not found"!
最佳答案
您需要捕获后台进程的进程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
现在当你运行它时:
bash tmp.sh
tmp.sh: line 6: FOOBAR: command not found
echo $?
127
关于bash - 从命名管道捕获非零退出代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53450561/