我有一个运行两个下标 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