bash 使用哪个 OR 运算符 - 管道 v 双管道
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41625521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash which OR operator to use - pipe v double pipe
提问by danday74
When I'm looking at bash script code, I sometimes see |
and sometimes see ||
, but I don't know which is preferable.
当我查看 bash 脚本代码时,我有时会看到|
有时会看到||
,但我不知道哪个更可取。
I'm trying to do something like ..
我正在尝试做类似的事情..
set -e;
ret=0 && { which ansible || ret=$?; }
if [[ ${ret} -ne 0 ]]; then
# install ansible here
fi
Please advise which OR operator is preferred in this scenario.
请告知在这种情况下首选哪个 OR 运算符。
回答by Charles Duffy
|
isn't an OR operator at all. You coulduse ||
, though:
|
根本不是 OR 运算符。不过,您可以使用||
:
which ansible || {
true # put your code to install ansible here
}
This is equivalent to an if
:
这相当于if
:
if ! which ansible; then
true # put your code to install ansible here
fi
By the way -- consider making a habit of using type
(a shell builtin) rather than which
(an external command). type
is both faster and has a better understanding of shell behavior: If you have an ansible
command that's provided by, say, a shell function invoking the real command, which
won't know that it's there, but type
will correctly detect it as available.
顺便说一句——考虑养成使用type
(shell 内置which
命令)而不是(外部命令)的习惯。type
速度更快,并且对 shell 行为有更好的理解:如果您有一个ansible
命令,例如,由调用实际命令的 shell 函数提供,which
则不会知道它在那里,但type
会正确地检测到它可用。
回答by ivanivan
There is a big difference between using a single pipe (pipe output from one command to be used as input for the next command) and a process control OR (double pipe).
使用单个管道(一个命令的管道输出用作下一个命令的输入)和过程控制 OR(双管道)之间存在很大差异。
cat /etc/issue | less
This runs the cat command on the /etc/issue file, and instead of immediately sending the output to stdout it is piped to be the input for the less command. Yes, this isn't a great example, since you could instead simply do less /etc/issue - but at least you can see how it works
这会在 /etc/issue 文件上运行 cat 命令,而不是立即将输出发送到 stdout,而是通过管道作为 less 命令的输入。是的,这不是一个很好的例子,因为你可以简单地做更少的 /etc/issue - 但至少你可以看到它是如何工作的
touch /etc/testing || echo Did not work
For this one, the touch command is run, or attempted to run. If it has a non-zero exit status, the double pipe OR kicks in, and tries to execute the echo command. If the touch command worked, then whatever the other choice is (our echo command in this case) is never attempted...
对于这个,触摸命令被运行,或试图运行。如果它具有非零退出状态,则双管道 OR 启动,并尝试执行 echo 命令。如果 touch 命令有效,那么无论其他选择是什么(在这种情况下我们的 echo 命令)都不会尝试......