bash shell 命令中“&&”的目的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4510640/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:00:06  来源:igfitidea点击:

What is the purpose of "&&" in a shell command?

bashshellcommand-linesyntax

提问by Captain

As far as I know, using &after the command is for running it in the background.

据我所知,&在命令之后使用是为了在后台运行它。

Example of &usage: tar -czf file.tar.gz dirname &

&用法示例:tar -czf file.tar.gz dirname &

But how about &&? (look at this example: https://serverfault.com/questions/215179/centos-100-disk-full-how-to-remove-log-files-history-etc#answer-215188)

但是&&呢?(看这个例子:https: //serverfault.com/questions/215179/centos-100-disk-full-how-to-remove-log-files-history-etc#answer-215188

回答by girasquid

&&lets you do something based on whether the previous command completed successfully - that's why you tend to see it chained as do_something && do_something_else_that_depended_on_something.

&&允许您根据上一个命令是否成功完成执行某些操作 - 这就是为什么您倾向于将其链接为do_something && do_something_else_that_depended_on_something.

回答by plundra

Furthermore, you also have ||which is the logical or, and also ;which is just a separator which doesn't care what happend to the command before.

此外,您还拥有||哪个是逻辑或,;哪个只是一个分隔符,它不关心之前命令发生了什么。

$ false || echo "Oops, fail"
Oops, fail

$ true || echo "Will not be printed"
$  

$ true && echo "Things went well"
Things went well

$ false && echo "Will not be printed"
$

$ false ; echo "This will always run"
This will always run

Some details about this can be found here Lists of Commandsin the Bash Manual.

关于此的一些详细信息可以在 Bash 手册中的命令列表中找到。

回答by Aaron Hall

command-line - what is the purpose of &&?

命令行 - 的目的是&&什么?

In shell, when you see

在 shell 中,当你看到

$ command one && command two

the intent is to execute the command that follows the &&only if the first command is successful. This is idiomatic of Posix shells, and not only found in Bash.

目的是&&只有在第一个命令成功时才执行后面的命令。这是 Posix shell 的惯用方式,不仅在 Bash 中发现。

It intends to prevent the running of the second process if the first fails.

如果第一个进程失败,它旨在阻止第二个进程的运行。

You may notice I've used the word "intent" - that's for good reason. Not all programs have the same behavior, so for this to work, you need to understand what the program considers a "failure" and how it handles it by reading the documentation and, if necessary, the source code.

你可能注意到我使用了“意图”这个词——这是有充分理由的。并非所有程序都具有相同的行为,因此要使其工作,您需要通过阅读文档和源代码(如有必要)了解程序认为“失败”的内容以及它如何处理它。

Your shell considers a return value of 0 for true, other positive numbers for false

你的 shell 认为返回值为 0 为真,其他正数为假

Programs return a signalon exiting. They should return 0 if they exit successfully, or greater than zero if they do not. This allows a limited amount of communication between processes.

程序在退出时返回一个信号。如果他们成功退出,他们应该返回 0,如果他们不成功,他们应该返回大于零。这允许进程之间进行有限数量的通信。

The &&is referred to as AND_IFin the posix shell grammar, which is part of an and_orlistof commands, which also include the ||which is an OR_IFwith similar semantics.

&&被称为AND_IFPOSIX壳语法,这是一个的一部分and_or列表的命令,其中还包括||其为OR_IF具有相似的语义。

Grammar symbols, quoted from the documentation:

从文档中引用的语法符号:

%token  AND_IF    OR_IF    DSEMI
/*      '&&'      '||'     ';;'    */
%token  AND_IF    OR_IF    DSEMI
/*      '&&'      '||'     ';;'    */

And the Grammar (also quoted from the documentation), which shows that any number of AND_IFs (&&) and/or OR_IFs (||) can be be strung together (as and_oris defined recursively):

和语法(也从文档中引用),它表明可以将任意数量的AND_IFs ( &&) 和/或OR_IFs ( ||) 串在一起(如and_or递归定义的那样):

and_or           :                         pipeline
                 | and_or AND_IF linebreak pipeline
                 | and_or OR_IF  linebreak pipeline
and_or           :                         pipeline
                 | and_or AND_IF linebreak pipeline
                 | and_or OR_IF  linebreak pipeline

Both operators have equal precedence and are evaluated left to right (they are left associative). As the docs say:

两个运算符具有相同的优先级并从左到右求值(它们是左结合的)。正如文档所说:

An AND-ORlist is a sequence of one or more pipelines separated by the operators "&&"and "||".

A list is a sequence of one or more AND-OR lists separated by the operators ';'and '&'and optionally terminated by ';', '&', or .

The operators "&&"and "||"shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output:

$ false && echo foo || echo bar
$ true || echo foo && echo bar

一个AND-OR列表是由运算符分隔的一个或多个管道的序列"&&""||"

列表是一个或多个的序列AND-OR列表分离由运营商';''&'和任选地被封端';''&'或。

运算符"&&"and"||"应具有相同的优先级,并应使用左结合性进行评估。例如,以下两个命令仅将 bar 写入标准输出:

$ false && echo foo || echo bar
$ true || echo foo && echo bar
  1. In the first case, the false is a command that exits with the status of 1

    $ false
    $ echo $?
    1
    

    which means echo foodoes not run(i.e., shortcircuiting echo foo). Then the command echo baris executed.

  2. In the second case, true exits with a code of 0

    $ true
    $ echo $?
    0
    

    and therefore echo foois not executed, then echo baris executed.

  1. 在第一种情况下,false 是一个以状态退出的命令 1

    $ false
    $ echo $?
    1
    

    这意味着echo foo不运行(即短路echo foo)。然后echo bar执行命令。

  2. 在第二种情况下, true 以代码退出 0

    $ true
    $ echo $?
    0
    

    因此echo foo不执行,则echo bar执行。

回答by Nigel Atkinson

A quite common usage for '&&' is compiling software with autotools. For example:

'&&' 的一个很常见的用法是用 autotools 编译软件。例如:

./configure --prefix=/usr && make && sudo make install

Basically if the configure succeeds, make is run to compile, and if that succeeds, make is run as root to install the program. I use this when I am mostly sure that things will work, and it allows me to do other important things like look at stackoverflow an not 'monitor' the progress.

基本上,如果配置成功,则运行 make 进行编译,如果成功,则以 root 身份运行 make 以安装程序。当我最确定事情会奏效时,我会使用它,它允许我做其他重要的事情,例如查看 stackoverflow 而不是“监视”进度。

Sometimes I get really carried away...

有时我真的被带走了......

tar xf package.tar.gz && ( cd package; ./configure && make && sudo make install ) && rm package -rf

I do this when for example making a linux from scratch box.

例如,我在从头开始制作 linux 时这样做。

回答by Dean Burge

&&strings commands together. Successive commands only execute if preceding ones succeed.

&&将命令串在一起。后续命令仅在前面的命令成功时才执行。

Similarly, ||will allow the successive command to execute if the preceding fails.

同样,||如果前面的命令失败,将允许执行后续命令。

See Bash Shell Programming.

请参阅Bash Shell 编程

回答by Nick

It's to execute a second statement if the first statement ends succesfully. Like an if statement:

如果第一条语句成功结束,则执行第二条语句。就像一个 if 语句:

 if (1 == 1 && 2 == 2)
  echo "test;"

Its first tries if 1==1, if that is true it checks if 2==2

如果 1==1,它第一次尝试,如果是真的,它检查是否 2==2

回答by alno

See the example:

看例子:

mkdir test && echo "Something" > test/file

Shell will try to create directory testand then, only if it was successfullwill try create file inside it.

Shell 将尝试创建目录test,然后,只有成功后才会尝试在其中创建文件。

So you may interrupt a sequence of steps if one of them failed.

因此,如果其中一个步骤失败,您可能会中断一系列步骤。

回答by Xiaonin Li

command_1 && command_2: execute command_2 only when command_1 is executed successfully.

command_1 && command_2: 仅当command_1 执行成功时才执行command_2。

command_1 || command_2: execute command_2 only when command_1 is not successful executed.

command_1 || command_2: 仅当command_1 没有成功执行时才执行command_2。

Feels similar as how an 'if' condition is executed in a mainstream programming language, like, in if (condition_1 && condition_2){...}condition_2 will be omitted if condition_1 is falseand in if (condition_1 || condition_2){...}condition_2 will be omitted if condition_1 is true. See, it's the same trick you use for coding :)

感觉类似于在主流编程语言中如何执行“if”条件,例如,if (condition_1 && condition_2){...}如果 condition_1 是false,则在if (condition_1 || condition_2){...}condition_2 中将省略,如果 condition_1 是,则在condition_2 中将被省略true。看,这与您用于编码的技巧相同:)

回答by Amin

####################### && or (Logical AND) ######################
first_command="1"
two_command="2"

if [[ ($first_command == 1) && ($two_command == 2)]];then
 echo "Equal"
fi

When program checks if command, then the program creates a number called exit code, if both conditions are true, exit code is zero (0), otherwise, exit code is positive number. only when displaying Equal if exit code is produced zero (0) that means both conditions are true.

当程序检查 if 命令时,程序会创建一个称为退出代码的数字,如果两个条件都为真,则退出代码为零 (0),否则,退出代码为正数。仅当退出代码产生零 (0) 时显示等于,这意味着两个条件都为真。