bash - 为什么在 bash 中使用管道命令与 && 连接命令时得到不同的结果?

标签 bash datetime command-line pipe

我为 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/

相关文章:

python - Applescript 包和 Python

python - 从编译输出动态导入运行时指定的模块

bash 陷阱不会忽略信号

python - 如何查找计算机上所有创建/修改时间晚于特定日期的文件?

windows - 输入为 dshow 时 ffmpeg 不停止

linux - bash vs csh vs 其他——哪个更适合应用程序维护?

python - 仅选择 Pandas 中每连续分钟都有数据的日期范围

json - DateTimes 反序列化错误 : JsonConvert is returning wrong dates

c - gcc 不会在 OS X 的命令行上包含 libcurl

python - 也可以作为命令行脚本运行的包结构