【问题标题】:documentation for "<<<" in bash shell [duplicate]bash shell 中“<<<”的文档 [重复]
【发布时间】:2016-10-13 14:46:52
【问题描述】:

以下工作在 bsd unix、bash shell 中:

stuff=$(echo "dog cat rat")

read -r -a astuff <<< "$stuff"

for file in "${astuff[@]}"; do echo "file=$file"; done

显然包含&lt;&lt;&lt; 的行将$stuff 分解为一个数组并将该数组放入astuff。但我不明白语法。 &lt;&lt;&lt; 是否有手册页或其他文档?这如何在空格处破坏字符串?

【问题讨论】:

标签: arrays bash shell variables


【解决方案1】:

这里叫做字符串。你可以阅读here

这里的字符串 这里文档的一种变体,格式为:

          [n]<<<word

   The word undergoes brace expansion, tilde expansion, parameter and
   variable expansion, command substitution, arithmetic expansion, and
   quote removal.  Pathname expansion and word splitting are not
   performed.  The result is supplied as a single string, with a newline
   appended, to the command on its standard input (or file descriptor n
   if n is specified).

【讨论】:

  • 不错。更直接的解释链接:tldp.org/LDP/abs/html/x17837.html.
  • 请不要链接到 ABS。它充满了错误和不良做法。这是official documentation的链接
  • @MarkA.Fitzgerald, ...如果你想要一些比 ABS 更受重视但比官方文档更正式的链接,你也可以考虑the bash-hackers wiki,或the Wooledge wiki(这里- 覆盖在页面底部附近的字符串)。 ABS 是 shell 脚本的 w3schools - 因传播不良做法和过时信息而臭名昭著。
  • 很好的直接链接,@chepner,感谢您对 ABS 质量的提醒。
  • @CharlesDuffy:很好地类比 w3schools re:ABS - 很高兴知道。
【解决方案2】:

read -r -a astuff <<< "$stuff"

...&lt;&lt;&lt; 是“here-string”语法,语法糖提供了一种更短的编写方式:

read -r -a astuff <<EOF
$stuff
EOF

read 因此是负责将您的内容分配到astuff 的命令; -a 参数告诉它将IFS 中的字符(默认为空格、制表符和换行符)拆分为一个数组。


参考资料:

...并且,在read 组件上:

【讨论】:

    【解决方案3】:

    您可以搜索man bash 以获得解释。这是一种可能的方式:

     $ man bash | grep -A10 -B4 "<<<"
    

    greps 在man bash 的输出中表示“

       Here Strings
           A variant of here documents, the format is:
    
                  <<<word
    
           The  word  undergoes  brace  expansion,  tilde expansion, parameter and
           variable expansion, command  substitution,  arithmetic  expansion,  and
           quote  removal.   Pathname  expansion  and  word splitting are not per‐
           formed.  The result is supplied as a single string to  the  command  on
           its standard input.
    

    还有另外 3 行,它们不相关。

    您可以对其他单词和您不理解的“单词”重复此搜索。

    【讨论】:

      猜你喜欢
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 2020-03-16
      • 2011-07-19
      • 2021-11-05
      相关资源
      最近更新 更多