Bang (!) 在 bash 中的使用

fra*_*ams 6 shell bash source pipe source-code

我正在阅读 bash 源代码,bash 的BNF 语法是:

<pipeline_command> ::= <pipeline>
                    |  '!' <pipeline>
                    |  <timespec> <pipeline>
                    |  <timespec> '!' <pipeline>
                    |  '!' <timespec> <pipeline>

<pipeline> ::=
          <pipeline> '|' <newline_list> <pipeline>
       |  <command>
Run Code Online (Sandbox Code Playgroud)

这是否意味着!命令也是一种管道。

! ls作品?但是它与ls.

! time ls 也有效。

这与|管道完全不同。

如何!在bash中使用?是管道吗?

Joh*_*éen 7

来自 bash 手册:“如果保留字 ! 在管道之前,则该管道的退出状态是退出状态的逻辑否定”

你误读了语法。语法上说你可以放一个 ! 在管道前面,而不是替换| 用一个!。


ilk*_*chu 5

感叹号只是在逻辑上反转命令/管道的返回码(参见例如Bash 的手册):

if true ;    then echo this prints ; fi
if ! false ; then echo this also prints ; fi
if ! true ;  then echo this does not print ; fi
Run Code Online (Sandbox Code Playgroud)

管道的返回码(通常)只是最后一个命令的返回码,因此 bang 将其反转:

if ! true | false ; then echo again, this also prints ; fi
Run Code Online (Sandbox Code Playgroud)