bash - 当其中一个后台进程出错时如何退出 bash 脚本?

标签 bash error-handling

<分区>

我有一个运行两个下标 t1 和 t2 的 bash 脚本。 t1 和 t2 都是后台进程,t1 会引发错误。我如何捕获此错误并完全退出整个脚本?

#!/bin/bash
set -e

error1() {
    echo "exit whole script!!!"
    exit 1
}

# this script will rise an error
./t1.sh &
pid1=$!


./t2.sh &
pid2=$!


wait $pid2

if [ $pid2 -eq 0 ]; then
    trap 'error1' ERR
fi


wait $pid1

if [ $pid1 -eq 0 ]; then
    trap 'error1' ERR
fi

最佳答案

思路是获取后台进程的返回码,据此做出判断。

#!/bin/bash
set -e
#set -o pipefail

error1() {
    echo 'err'
    exit 1
}

# this script (process) will rise an error
./t1.sh &
pid_1=$!  # Get background process id


# Getting the process-id of the second process
./t2.sh &
pid_2=$!  

# If either of the processes crash with a non-zero error code, wait returns  
# '0' and the 'if' condition fails.

if  wait $pid_1 && wait $pid_2
then
    echo -e "Processes termination successful"
else
    trap 'error1' ERR  # Either of P1 or P2 has terminated improperly
fi

关于bash - 当其中一个后台进程出错时如何退出 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36882936/

相关文章:

linux - 自动化 Linux 软件安装

linux - 如何从 bash 脚本启动程序,然后关闭终端但让程序保持事件状态

linux - (标准输入) 1 : parse error

bash - 如何在 macOS/Linux bash 中验证 jq 1.5 中的查询?

postgresql - postgresql 检查约束的自定义错误消息

r - 使用Shiny中的if/else block 进行警告处理

bash - 使用另一个列表中的名称重命名文件列表

linux - 如何在Linux中跟踪在安装APP期间在哪里安装文件?

bash - 在bash中包装一个perl脚本-向IRC机器人回显

error-handling - .PNG似乎可以在某些浏览器中使用,但不能在所有浏览器中使用