【问题标题】:Two different ways for reading from stdin从标准输入读取的两种不同方式
【发布时间】:2019-05-09 18:38:05
【问题描述】:

很难用谷歌搜索这个,我有这个:

echo "age" |  while read line; do
    echo "$line"
done

但是有这种风格:

while read line; do
    echo "$line"
done < echo "age"

首先,第二种样式不太对,但是第一种和第二种样式有名称吗?有任何功能/行为差异吗?

【问题讨论】:

  • 第一个是流水线,第二个是重定向
  • &lt; echo "age" 将尝试从名为 echo 的文件中读取输入。 &lt; 是文件重定向。你想要的是&lt; &lt;(echo "age")&lt;&lt;&lt; "age""
  • &lt;(echo "age")进程替换&lt;&lt;&lt; "age"here-string
  • 但你可能想要heredoc:while read line; do ...; done &lt;&lt; EOF

标签: bash shell pipe


【解决方案1】:

最大的功能区别是第一个(在 bash 中)将在子 shell 中运行循环。因此,$line 将在循环完成后失去其值。为避免 subshel​​l,您可以使用 heredoc 将内容直接嵌入到 shell 中:

while read line; do
    echo "$line"
done << EOF
age
EOF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 2012-02-17
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多