破折号:从管道读取变量

Mar*_*ter 1 shell dash

bashor 中zsh,我可以使用以下语法从管道读取到变量:

echo AAA BBB | read X Y ; echo $X
Run Code Online (Sandbox Code Playgroud)

这将打印 AAA

为什么同样不起作用/bin/sh

我在 Debian 中使用/bin/sh-> /bin/dash dash

pLu*_*umo 5

为什么同样在 '/bin/sh' 中不起作用?

在管道中分配变量不会按预期工作shbash因为管道的每个命令都在子 shell 中运行。事实上,命令不工作XY得到声明,但他们不具备的管外。

以下将起作用:

echo AAA BBB | { read X Y ; echo $X; }
Run Code Online (Sandbox Code Playgroud)

但在你的情况下:

尝试这个,

read X Y <<< "AAA BBB"
Run Code Online (Sandbox Code Playgroud)

或者

read X Y < <(echo "AAA BBB")
Run Code Online (Sandbox Code Playgroud)

一些有用的链接:

  • 对我来说,它在 bash (4.3.48) 中不起作用。 (2认同)