为什么带有命令替换 herestring 的 Bash 'while' 读取循环不读取整个输入?

Bob*_*421 3 bash command-substitution read here-string

看看这个非常基本的 Bash 脚本:

#!/bin/bash
while read l
do
  echo $l
  echo "next one"
done <<< $(ps aux)
Run Code Online (Sandbox Code Playgroud)

我的计算机上有多个进程,该ps aux命令在终端中运行良好。

我在循环中只得到一次迭代,ps命令输出在同一行给出。为什么它不能按预期工作?

pLu*_*umo 7

bash版本 <4.4-beta您需要添加双引号:

#!/bin/bash
while read l
do
  echo $l
  echo "next one"
done <<< "$(ps aux)"
Run Code Online (Sandbox Code Playgroud)

看:


一般来说,我认为最好使用进程替换:

#!/bin/bash
while read l
do
  echo $l
  echo "next one"
done < <(ps aux)
Run Code Online (Sandbox Code Playgroud)

(为避免出现问题,您可能需要使用IFS=)。

或者更好的是,使用专门用于读取文件或逐行输入的程序,例如awk.

ps aux | awk '{print $0; print "next one"}'
Run Code Online (Sandbox Code Playgroud)

  • @Bob5421 因为这是一个在较新版本的 bash 中修复的错误。现在 `&lt;&lt;&lt; $(...)` 应该与 `&lt;&lt;&lt; "$(...)"` 相同(特别是与 `&lt;&lt;&lt;` 一起使用时,而不是 `$(...)`一般的)。我可以用 bash-3.2 重现您的问题,但不能用较新的版本重现。 (2认同)