在使用&&时如何执行退出命令和||? [英] How to execute exit command while using && and ||?
问题描述
我有两种情况.
-
回显&/dev/null&&回声b ||(回声c;出口1);echo d; echo e; echo f
输出:
b
d
e
f
-
回显&/dev/null&&回声b ||(回声c;出口1);echo d; echo e; echo f
输出:
c
d
e
f
我需要我的脚本在退出命令后退出,并且不执行其他命令.我该怎么办?
I need my script to exit after the exit command and not execute further commands. How I can do it?
推荐答案
()
中的命令在子shell中执行,因此parens中的 exit
仅退出子shell,不是主要的外壳.您可以使用 {}
而不是parens来对命令不进行分组,而不强制使用子外壳.注意:与括号不同,您需要在 {
之后加上一个空格,并在}
之前使用一个分号(或&"号).
Commands in ( )
are executed in a subshell, so exit
inside parens only exits the subshell, not the main shell. You can group commands without forcing a subshell using { }
instead of parens. Note: unlike with parens, you need a space after the {
, and a semicolon (or ampersand) before }
.
$ eco a &>/dev/null && echo b || { echo c ; exit 1; } ; echo d ;echo e;echo f output
c
logout
此外,您还应该注意使用&&... ||
与结构相同,否则为fi
结构;特别是如果&
和 ||
之间的命令(与 if
语句)应该碰巧失败,它也会执行 ||
之后的内容.仅使用 echo b
,它不太可能(但从技术上来说)失败.如果比较复杂,您会得到意想不到的结果.
Also, you should be aware that using && ... ||
is not the same as an if then else fi
structure; in particular, if the command between &&
and ||
(which corresponds to the then
clause in an if
statement) should happen to fail, it'll execute what's after the ||
as well. With just echo b
in there, it's unlikely (but technically possible) for it to fail; if it's more complicated, you can get unexpected results.
因此,我建议使用 if然后else fi
代替&&|||
-可以正确处理分组,而不会带来额外的麻烦,并且没有明显的执行路径.与&&||
,它就可以工作.
As a result, I recommend using if then else fi
instead of && ||
-- it handles the grouping properly without additional hassle, and doesn't have non-obvious execution paths. Unlike && ||
, it just works.
这篇关于在使用&&时如何执行退出命令和||?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!