4
我为current_datetime实现了一个小的python函数,并将其插入到bash脚本中。与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
但是,如果我跑下一行几次,我得到了相同的结果(注加粗)
$ 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。 – blackghost