【问题标题】:Why do I got different results when using piped commands in contrast to && concatenated commands in bash?与 bash 中的 && 连接命令相比,为什么在使用管道命令时会得到不同的结果?
【发布时间】: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


【解决方案1】:

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

$ FOO=bar | echo $FOO

$ echo $FOO

$

list 中由&& 分隔的命令是按顺序执行的,而不是在子shell 中。

$ FOO=bar && echo $FOO
bar
$

另一种生成子shell的方法是with parentheses

$ (FOO=bar) && echo $FOO

$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-25
    • 2012-01-31
    • 1970-01-01
    • 2021-12-29
    • 2011-01-06
    • 2015-07-20
    • 1970-01-01
    相关资源
    最近更新 更多