bash:从source-d脚本退出 [英] bash: exit from source-d script

查看:252
本文介绍了bash:从source-d脚本退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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 sourced 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆