繁体   English   中英

为什么shell中的“false -a true”和“true -a false”返回不同的结果?

[英]Why ”false -a true“ and "true -a false" in shell return a different results?

IMO, -a&&都是 shell 中and操作,所以我假设true -a falsefalse -a true都会返回“false”。 那么事实是

[root@master ~] true -a false
[root@master ~] echo $?
0
[root@master ~] false -a true
[root@master ~] echo $?
1
[root@master ~] a=[ true -a false ]
[root@master ~] echo $a
true
[root@master ~] a=[ false -a true ]
[root@master ~] echo $a
true

为什么会发生这种情况,如果我想在壳牌中操作and我应该怎么做?

让我们在 shell 中的命令的一般语法是:

[var=val...] cmd [args...]

var=val在命令cmd的持续时间内使用值val导出环境变量var

为什么会发生这种情况

命令truefalse都忽略参数。 true anything以 0 退出状态退出, false anything以非零退出状态退出。 true -a false使用两个参数执行命令true , sting -a和 string false true忽略参数,以零退出状态退出。 相同的false

a=[将值为字符串[的变量a导出到下一个命令的环境。

$ a=[ env | grep '^a='
a=[

a=[ true -a false ]将环境变量a设置为字符串[的值,然后使用 3 个参数 string -a 、字符串false和字符串]执行命令true

  a=[ true -a false ]
  |   |    |  |     \----  third argument
  |   |    |  \----------  second argument
  |   |    \-------------  first argument
  |   \------------------  command to execute
  \----------------------  var=val, exports a variable

true忽略参数,再次为true ,退出状态0 false也是如此,退出状态非零。

显示true的值echo $a是您之前在 shell 中设置的值。 a=[ true ...仅在命令的持续时间内设置变量a ,之后变量具有自己的值。

$ a=anything_here
$ a=anything_here2 true anything_here3
$ echo $?
0               # true exits with 0 exit status
$ echo $a
anything_here   # the variable `a` preserved its value set before the command

为什么shell中的“false -a true”和“true -a false”返回不同的结果?

因为命令falsetrue以不同的退出状态退出。

注意:字符串true false [ ] -a对于 shell 没有特殊含义。 这些都是字符串。 当作为命令[的参数传递时,字符串-a]具有特殊含义。 它仍然是字符串-a ,但是当可执行文件[被执行时,它会解析参数并专门作用于字符串-a 恰好有名为truefalse的可执行文件。 字符串[ , ]truefalse-a本身对 shell 没有意义,这些都只是字符串。

-a 和 && 都是和 shell 中的操作,

不, -a是 shell 中的字符串-a &&是 shell 中的“与”操作。 -a[test commands的“与”运算符。 注意:由于[的问题,更喜欢使用[ ... ] && [ ... ]而不是[ ... -a ... ]

参考: https ://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/test.html,https: //www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Simple-Command -扩展, https : //pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/true.html,https : //pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/false.html,https ://pubs .opengroup.org/onlinepubs/009604499/utilities/xcu_chap02.html#tag_02_09_01

感谢 KamilCuk 的回答。 读完之后,这是我的简短版本。

true -a falsefalse -a true只是一个包含两个参数的命令(-a [false/true])。 它的退出代码取决于分别返回 0 和 1 的命令本身。

a=[ true -a false相同,但变量a在执行true -a false之前被设置为'['

如果未设置a则应取消set -a否则它将是'['

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM