• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

设置-e和短期测试

用户头像
it1352
帮助1

问题说明

当我是新来的shell脚本,我用了很多的短期测试,而不是如果语句,如假放;&安培;真正

When I was new to shell scripting, I used a lot of short tests instead of if statements, like false && true.

再后来我学会了使用设置-e 时,发现我的脚本是死于因某种原因,如果我取代了简短的测试以饱满他们将努力如果语句。现在,时代已经一去不复返了,而我还在用充满如果语句只。

Then later I learned using set -e, and found my scripts were dying for some reason, and they would work if I replaced the short tests with full if statements. Now, the time has gone, and I still use full if statements only.

最有趣的是,如果我打开一个交互的shell并执行以下操作:

The most interesting is that if I open an interactive shell and do the following:

set -e
false && true
echo $?

则返回1,但shell不会死!

我看到,我已经浪费了code过多的线条。我该如何使用设置-e 短的测试安全,如任何人都可以向我解释。没有剧本死去?

I see that I have been wasting too many lines of code. Anyone could explain to me how can I use set -e with short tests safely, eg. without the script dying?

正确答案

#1

对于我的剧本意外死去的问题,这是由于在子shell中运行这些短期测试。

Regarding my problem of the script unexpectedly dying, it is due to running those short tests in a subshell.

原来的例子:

$ set -e
$ false && true
$ echo $?
1

使用子shell:

Using a subshell:

$ set -e
$ (false && true)
<script died>

$ set -e
$ variable=$(false && true)
<script died>

$ set -e
$ foo()(false && true)
$ foo
<script died>

$ set -e
$ foo(){ false && true; }
$ foo
<script died>

可能的解决方案:

Possible solutions:

$ set -e
$ (false && true ||:)
$ (false && true) ||:
$ (if false; then true; fi)

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfgihf
系列文章
更多 icon
同类精品
更多 icon
继续加载