当bash脚本的一个后台进程出错时,如何退出该脚本?
我有一个运行两个下标t1和t2的bash脚本。 t1和t2都是后台进程,t1将引发错误。如何捕获此错误并完全退出整个脚本当bash脚本的一个后台进程出错时,如何退出该脚本?,bash,error-handling,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 ];
#!/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
是否可以将t1和t2作为后台进程运行,并在其中任何一个出现错误时终止脚本?是的,这是可能的。在两个进程id上的
wait
中添加一个bash条件,并执行相应的操作。我尝试了您的建议,但仍然无法使其工作,它没有转到error1()。你能看一下吗?我已经编辑了上面的代码。非常感谢你更新了答案,如果有用的话就接受它。谢谢,但我没法让它工作。我试图在t1.sh中引发错误,但未捕获错误。t1.sh#的代码/bin/bash集-e run1(){return 1}run1