bash:从source-d脚本退出 [英] bash: exit from source-d script
问题描述
我的bash脚本使用了很多检查,例如:
My bash script uses a lot of checks like:
if [ something bad ] ; then
echo "error message"
exit 1
fi
我发现,如果用户通过source my-script.sh
而不是./my-script.sh
执行它,则此exit 1
会关闭用户的外壳程序!
用户看不到任何错误消息!
I have found out that if the user executes it via source my-script.sh
rather than ./my-script.sh
, this exit 1
closes the user's shell !
And the user sees no error message !
我如何知道该脚本是source-d,以及如何退出(使用非零状态代码)source-d脚本?一般来说,我该怎么办?
How do I know that the script is source-d, and how do I exit (with non-zero status code) the source-d script? In general, what can I do about this?
推荐答案
似乎有两部分.首先是要知道何时在source
d脚本中执行而不是在已执行的脚本中执行.可以在此答案中找到,对于bash,他们建议:
It seems there could be 2 parts to this. The first is to know when you're executing in a source
d script instead of an executed one. That can be found in this answer, and for bash they suggest:
[[ "$0" != "$BASH_SOURCE" ]] && sourced=1 || sourced=0
告知您是否被派遣.
如果您是来源人,则希望使用return
而不是exit
.
If you are being sourced, you'd want to use return
instead of exit
.
您可以将该函数存储在类似这样的变量中
You could store that function in a variable with something like
if [[ $sourced -eq 1 ]]; then
ret=return
else
ret=exit
fi
,然后当您想使用合适的那一个时就使用
and then when you want to use the appropriate one you'd just use
$ret 1
这篇关于bash:从source-d脚本退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!