2017-08-29 71 views
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** 

什么是在同一个命令行和确切时刻了实现这些方面执行时|&&之间的区别是什么?

+1

一个是管,另一个是逻辑和。在第一个例子中,它将'DT'设置为一个值,然后将输出管道输送到'echo $ DT'。设置'DT'发生在一个子shell中,并且不会影响'echo $ DT'运行的环境,或者甚至下一行运行。在&&中它运行第一个命令,它设置'DT',并且因为没有失败,它执行第二个命令并设置了DT。 – blackghost

回答

4

pipeline中的每个命令都在其自己的子shell中执行。这意味着变量赋值没有任何作用。

$ FOO=bar | echo $FOO 

$ echo $FOO 

$ 

而在由&&分离的list的命令被顺序执行,而不是在一个子shell。

$ FOO=bar && echo $FOO 
bar 
$ 

另一种产生子外壳的方法是with parentheses

$ (FOO=bar) && echo $FOO 

$ 
相关问题