【发布时间】:2018-02-07 05:48:36
【问题描述】:
我为 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**
| 和&& 在同一命令行中的实现以及执行它们的确切时间方面有什么区别?
【问题讨论】:
-
一个是管道,另一个是逻辑与。在您的第一个示例中,它将
DT设置为一个值,然后将输出通过管道传输到echo $DT。设置DT发生在子shell 中,不会影响运行echo $DT的环境,甚至不会影响运行下一行的环境。在&&中,它运行第一个命令,设置DT,并且因为没有失败,它执行设置DT的第二个命令。
标签: bash datetime command-line pipe