嗯,关于源脚本中的错误拦截后原作者想要什么并不是很清楚,但以下作为解决方案入口:
您可以在 ERR 上设置陷阱,并在其中处理源脚本中的错误。以下有两种情况:一个是源脚本使用了“set -e”,另一个是源脚本没有使用“set -e”。
主要脚本使用定义了“set -e”的次要脚本,并捕获了错误:
[galaxy => ~]$ cat primary.sh
set -e
echo 'Primary script'
trap 'echo "Got an error from the secondary script"' ERR
source secondary.sh
trap - ERR
echo 'Primary script exiting'
[galaxy => ~]$ cat secondary.sh
echo 'Secondary script'
set -e
echo 'Secondary script generating an error'
false
echo 'Secondary script - should not be reached'
[galaxy => ~]$ ./primary.sh
Primary script
Secondary script
Secondary script generating an error
Got an error from the secondary script
[galaxy => ~]$
主要脚本在不带“set -e”参数的情况下调用次要脚本,并捕获错误:
[galaxy => ~]$ cat primary.sh
set -e
echo 'Primary script'
trap 'echo "Got an error from the secondary script"' ERR
source secondary.sh
trap - ERR
echo 'Primary script exiting'
[galaxy => ~]$ cat secondary.sh
echo 'Secondary script'
echo 'Secondary script generating an error'
false
echo 'Secondary script - should not be reached if sourced by primary.sh'
[galaxy => ~]$ ./primary.sh
Primary script
Secondary script
Secondary script generating an error
Got an error from the secondary script
[galaxy => ~]$
作为一个额外的奖励:拦截源脚本中的错误并继续执行:
[galaxy => ~]$ cat primary.sh
echo 'Primary script'
i=0
while [ $i = 0 ]; do
i=1
trap 'echo "Got an error from the secondary script"; break' ERR
source secondary.sh
done
trap - ERR
echo 'Primary script exiting'
[galaxy => ~]$ cat secondary.sh
echo 'Secondary script'
echo 'Secondary script generating an error'
false
echo 'Secondary script - should not be reached if sourced by primary.sh'
[galaxy => ~]$ ./primary.sh
Primary script
Secondary script
Secondary script generating an error
Got an error from the secondary script
Primary script exiting
[galaxy => ~]$