你怎么能要求的bash当前的选项? [英] How can you ask bash for the current options?

查看:143
本文介绍了你怎么能要求的bash当前的选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多内置的bash脚本和其他工具的系统工作。
相当频繁,我认为这是很好的做法,使用-e,-u和-o选项pipefail捕捉错误情况和prevent意外行为。

I am working with a number of systems built of bash scripts and other tools. Fairly often, I consider it good practice to use the -e, -u and -o pipefail options to catch error conditions and prevent unexpected behaviour.

然而,一些第三方库(而我不得不改变源代码的能力)不这样做,并且不开心改变变量测试,-u存在的。

However, some of the third party libraries (to which I have the ability to change source) do not do this, and are not happy with altering variable tests to exist with -u.

在这些中的脚本可能被源不执行。所以我希望做的是一些这些,设置一个更宽松的选项,然后恢复严格的。由于有问题的脚本由许多用户,其中一些人也遇到同样的问题时,我愿意把这种变化纳入第三方脚本,即:

The scripts in those are likely to be sourced not executed. So what I'd like to do is in some of these, set a more permissive set of options, and then restore the stricter ones. Since the scripts in question are used by many users, some of whom have also encountered the same problem, I'd want to put this change into the third party scripts ie:

<preserve original options>
set +e +u +o pipefail
#do stuff like
if [ -n "$_UNSET_VAR" ] ; then
  cp <some stuff> <some other stuff>
fi
<restore original options (whatever they were)>

我要寻找方法来preserve和恢复这些原稿。

I am looking ways to preserve and restore these originals.

推荐答案

特殊参数 $ - 包含当前设置的选项列表。您可以解析,看看 -e -u 设置。对于 pipefail ,你必须分析的输出禁用了javascript

The special parameter $- contains a list of the options that are currently set. You can parse that to see if -e and -u are set. For pipefail, you'll have to parse the output of shopt.

如果您可以在子shell中运行code(你是不是要设置全局变量等),也可能是更容易做到这一点,而不是担心重置原来的状态。

If you can run your code in a subshell (you aren't trying to set global variables and the like), it may be easier to do that and not worry about resetting the original state.

(
    set +e +u +o pipefail
    if [ -n "$_UNSET_VAR" ]; then
       cp <some stuff> <some other stuff>
    fi
)

这篇关于你怎么能要求的bash当前的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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