在某些情况下,您希望从函数内部终止脚本:
function die_if_fatal(){
....
[ fatal ] && <termination statement>
}
Run Code Online (Sandbox Code Playgroud)
如果脚本来源为 ,$ . script并且终止语句为:
return,正如预期的那样,将从die返回,但不会完成脚本exit 终止会话(不返回脚本)。现在,如果脚本被执行chmod +x script; ./script:
return,正如预期的那样,将从die返回,但不会完成脚本exit 不会返回die并终止脚本。简单的方法是使用返回代码并在返回时检查它们,但是,我需要停止父级,而不修改调用者脚本。
有其他方法可以解决这个问题,但是,假设您在 5 级进入一个复杂的脚本,并且您发现脚本必须结束;也许是一个“魔法”退出代码?我只想要源代码上的执行行为。
我正在寻找一个简单的语句来结束正在运行的源脚本。
采购时,从函数内部完成脚本的正确方法是什么?
假设您的脚本不是来自循环内部,您可以将脚本的主体封装到人工运行一次循环中,并使用命令中断脚本break。
正式化这个想法并提供一些支持实用程序,您的脚本必须具有以下结构:
#!/bin/bash
my_exit_code=''
bailout() {
my_exit_code=${1:-0}
# hopefully there will be less than 10000 enclosing loops
break 10000
}
set_exit_code() {
local s=$?
if [[ -z $my_exit_code ]]
then
return $s
fi
return $my_exit_code
}
###### functions #######
# Define your functions here.
#
# Finish the script from inside a function by calling 'bailout [exit_code]'
#### end functions #####
for dummy in once;
do
# main body of the script
#
# finish the script by calling 'bailout [exit_code]'
done
set_exit_code
Run Code Online (Sandbox Code Playgroud)