当bash脚本的后台进程之一出现错误时,如何退出bash脚本?

Mic*_*ael 5 error-handling bash

我有一个运行两个下标 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
Run Code Online (Sandbox Code Playgroud)

Ini*_*ian 2

想法是获取后台进程的返回码并做出相应的决定。

#!/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
Run Code Online (Sandbox Code Playgroud)