设置-e和短期测试
问题说明
当我是新来的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?
正确答案
对于我的剧本意外死去的问题,这是由于在子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
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
检查邮件是否发送成功
it1352 07-25 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22