如何停止脚本执行可能已经采购或直接执行 [英] How to stop execution in script which may have been sourced or directly executed
问题描述
如果我的脚本获取与采购
If my script gets sourced with
. ./my_script.sh
source ./my_script.sh
然后在脚本停止执行,我会使用收益
。
如果我的脚本直接与执行
If my script is directly executed with
./my_script.sh
bash ./my_script.sh
然后我会插入一个退出
。
如果我不知道用户是否会采购或直接执行它,我怎么能干净地停止脚本,而不杀死它是由被称为终端?
preferably中,code段应能够终止,即使它被放在里面的脚本的功能之一的脚本。
Preferably, the code snippet should be able to terminate the script even if it were placed inside one of the script's functions.
推荐答案
请尝试以下操作:
ec=0 # determine the desired exit code
return $ec 2>/dev/null || exit $ec
收益
会成功,如果脚本正在来源,否则退出
将一命呜呼了 2 - ;的/ dev / null的
燮$ p $的情况下,psses错误消息剧本的不的来源
return
will succeed if the script is being sourced, otherwise exit
will kick in. The 2>/dev/null
suppresses the error message in case the script is not sourced.
净效果是,该脚本将与所需的退出/返回code终止,不管它是否被源或不
The net effect is that the script will terminate with the desired exit / return code, regardless of whether it was sourced or not.
更新:在OP希望能够从的退出脚本中的一个函数的内部脚本
Update: The OP wants to be able to exit the script from inside a function within the script.
我能想到的唯一的办法是为将所有脚本的code在一个的子shell 的并调用退出
从子shell里面的功能在里面;然后将回报2 - ;的/ dev / null的||退出
命令的之后的子shell(作为子shell之外唯一语句):
The only way I can think of is to place all of your script's code in a subshell and call exit
from inside the functions inside that subshell; then place the return 2>/dev/null || exit
command after the subshell (as the only statement outside the subshell):
#!/usr/bin/env bash
( # subshell to place all code in
foo() {
exit 1 # exit the subshell
}
foo # invoke the function
)
# Terminate script with exit code from subshell.
ec=$?; return $ec 2>/dev/null || exit $ec
这篇关于如何停止脚本执行可能已经采购或直接执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!