我为 current_datetime 实现了一个小的 python 函数并将它插入到 bash 脚本中。
$ current_datetime
2017-08-29 12:01:18.413240
后来,我把它赋给了一个变量
$ DT=$(current_datetime)
我可以打电话
$ echo $DT
2017-08-29 12:03:48.213455 #and get a time some seconds later for sure
但是如果我多次运行下一行,我会得到相同的结果(注意 bold 中相同的秒小数部分)
$ DT=$(current_datetime) | echo $DT
2017-08-29 12:04:42.**544683**
$ DT=$(current_datetime) | echo $DT
2017-08-29 12:04:42.**544683**
$ DT=$(current_datetime) | echo $DT
2017-08-29 12:04:42.**544683**
反过来,当我使用 &&
而不是 |
时,我得到了每次按下 Enter
按钮时的准确时间。为什么?
$ DT=$(current_datetime) && echo $DT
2017-08-29 12:21:**11.564654**
$ DT=$(current_datetime) && echo $DT
2017-08-29 12:21:**13.522406**
$ DT=$(current_datetime) && echo $DT
2017-08-29 12:21:**14.744963**
|
和 &&
在同一命令行中的实现以及它们执行的确切时刻有何不同?
最佳答案
pipeline 中的每个命令在它自己的子 shell 中执行。这意味着变量赋值没有任何效果。
$ FOO=bar | echo $FOO
$ echo $FOO
$
而 list 中的命令由 &&
分隔的顺序执行,而不是在子 shell 中执行。
$ FOO=bar && echo $FOO
bar
$
另一种生成子 shell 的方法是 with parentheses .
$ (FOO=bar) && echo $FOO
$
关于bash - 为什么在 bash 中使用管道命令与 && 连接命令时得到不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944727/