【问题标题】:while read bash array (not into)同时读取 bash 数组(不进入)
【发布时间】:2016-09-27 00:05:11
【问题描述】:

我正在尝试使用带有while read 的数组,但会立即输出整个数组。

#!/bin/bash

declare -a arr=('1:one' '2:two' '3:three');

while read -e it ; do
    echo $it
done <<< ${arr[@]}

它应该单独输出每个值(但不输出),所以也许 while read 不是这里的热门票?

【问题讨论】:

  • cat &lt;&lt;&lt; ${arr[@]} 将所有元素放在同一行。
  • @couling:我也试过&lt;&lt;&lt;,但并没有真正明白。

标签: linux bash macos while-loop


【解决方案1】:

可能通过while循环

#!/bin/bash

declare -a arr=('1:one' '2:two' '3:three');
len=${#arr[@]}
i=0
while [ $i -lt $len ]; do
    echo "${arr[$i]}"
    let i++
done

【讨论】:

    【解决方案2】:

    对于这种情况,使用for 循环会更容易:

    $ declare -a arr=('1:one' '2:two' '3:three')
    $ for it in "${arr[@]}"; do echo $it; done
    1:one
    2:two
    3:three
    

    while read 方法非常有用 (a) 当您想要从文件中读取数据时,以及 (b) 当您想要读取 nul 或换行符分隔的字符串时。但是,在您的情况下,您已经在 bash 变量中拥有数据,并且 for 循环更简单。

    【讨论】:

    • while 循环是否无法读取数组,或者我可以在数组中添加换行符字符串,以便读取文件的行为?只是很好奇……谢谢!
    • @CocoaPuffs -- 您可能需要第二个 while 循环来回显(写)出数据,以便您可以读取它 -- 因此尝试使用 while 循环不是一个好的解决方案
    • @CocoaPuffs 该数组已经是一个 bash 变量。使用 while read 意味着将其作为字符串从 bash 变量中取出,read 然后将其重新处理为新的 bash 变量。我确信在某些情况下这很有用,但很少见。
    • @CocoaPuffs 如果您真的想这样做,您可以使用带有 read 的 -d 标志来设置分隔符。但这不被推荐。 ss64.com/bash/read.html
    • 这就是我的想法,但无论如何都想问一下(如果有这种罕见的情况)。谢谢大家(@John1024、@Soren、@couling)!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 2017-04-21
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多