从命名管道捕获非零退出代码 [英] Capture non-zero exit code from named pipe
本文介绍了从命名管道捕获非零退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
即使发送到命名管道的过程失败,以下玩具脚本(tmp.sh
)也会以代码0退出.如何从命名管道中捕获非零退出代码?或更普遍地说,某事出了错?
The following toy script (tmp.sh
) exits with code 0 even if the process sent to the named pipe fails. How can I capture the non-zero exit code from the named pipe? Or more in general, the fact that something has gone wrong?
#!/bin/bash
set -eo pipefail
mkfifo mypipe
FOOBAR > mypipe &
cat mypipe
运行并检查退出代码:
Run and check exit code:
bash tmp.sh
tmp.sh: line 6: FOOBAR: command not found
echo $? # <- Exit code is 0 despite the "command not found"!
推荐答案
您需要捕获后台进程的进程ID,并wait
为其设置正确的退出状态:
You need to capture process id of background process and wait
for it to set the correct exit status:
#!/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
这篇关于从命名管道捕获非零退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文