Bash 正在检查后台进程的可能退出代码

Bash 正在检查后台进程的可能退出代码,bash,Bash,考虑以下代码: myprocess | while read line; do logger -t mytag -p user.err $line; done & if [ ${PIPESTATUS[0]} -ne 0 ]; then logger -t ${tag} -p user.error "CANNOT START (exit code: ${PIPESTATUS[0])" fi 如果myprocess没有失败,那么管道状态[0]是什么,未定义? 如何检查myproce

考虑以下代码:

myprocess | while read line; do logger -t mytag -p user.err $line; done &

if [ ${PIPESTATUS[0]} -ne 0 ]; then
   logger -t ${tag} -p user.error "CANNOT START (exit code: ${PIPESTATUS[0])"
fi
如果myprocess没有失败,那么管道状态[0]是什么,未定义? 如何检查myprocess是否在启动时启动或停止(缺少库符号等),同时仍捕获其输出

谢谢, 丹

这个怎么样:

{ myprocess 2>&1 || echo "CANNOT START (exit code: $?)" ; } \
| while read line; do logger -t mytag -p user.err $line; done

2>&1
将允许您捕获和记录错误输出以及标准输出。

如果
myprocess
没有失败,
${PIPESTATUS[0]}
将为
0


或者,
设置-o pipefail
。如果
myprocess
失败,则完整命令(
$?
)的退出状态将为非零,并且您无需检查
PIPESTATUS
,这可能会变得棘手。您需要从后台作业返回${PIPESTATUS[n]}。我做了一些非常类似的事情,创建一个函数并传入命令作为参数运行,然后将整个过程发送到后台。注意pipe_command()函数中的return语句。这将返回$cmd的状态,而不是while read line循环。您也可以使用此技术在for循环中为多个内容设置背景。希望这有帮助

例如:

#! /bin/bash

main()
{
    pids=""
    myprocess="ssh user@node /bin/bash /etc/init.d/process start"
    pipe_command "$myprocess" &
    pids+="$! "
    watch_pids "$pids"
}

pipe_command()
{
    cmd="$1"
    $cmd 2>&1 | \
    while read line; do
        logger -t mytag -p user.err $line
    done
    return ${PIPESTATUS[0]}
}

watch_pids()
{
    pids="$1"
    for pid in $pids; do
        wait $pid
        if [ $? -ne 0 ]; then
            logger -t ${tag} -p user.error "CANNOT START (exit code: $?)"
            return 2
        fi
    done
}
main $@
或者更简单地说,以你的例子:

myprocess | while read line; do logger -t mytag -p user.err $line; done ; return ${PIPESTATUS[0]} &

wait
status=$?
if [ $status -ne 0 ]; then
   logger -t ${tag} -p user.error "CANNOT START (exit code: $status)"
fi

PIPESTATUS
适用于最新的前台管道。如果在完成后添加一个&。脚本需要继续,将其保留在后台。