【问题标题】:Can I read line from a heredoc in bash?我可以从 bash 中的heredoc 中读取行吗?
【发布时间】:2011-01-21 05:04:09
【问题描述】:

这就是我正在尝试的。我想要的是最后一个 echo 在循环时说“一二三四 test1 ...”。它不工作; read line 空了。这里有什么微妙之处吗?或者这根本行不通?

array=( one two three )
echo ${array[@]}
#one two three
array=( ${array[@]} four )
echo ${array[@]}
#one two three four


while read line; do
        array=( ${array[@]} $line )
        echo ${array[@]}
done < <( echo <<EOM
test1
test2
test3
test4
EOM
)

【问题讨论】:

  • array+=("four")array+=("$line")

标签: bash heredoc


【解决方案1】:

我通常会写:

while read line
do
    array=( ${array[@]} $line )
    echo ${array[@]}
done <<EOM
test1
test2
test3
test4
EOM

或者,更有可能:

cat <<EOF |
test1
test2
test3
test4
EOF

while read line
do
    array=( ${array[@]} $line )
    echo ${array[@]}
done

(请注意,带有管道的版本不一定适用于 Bash。Bourne shell 将在当前 shell 中运行 while 循环,但 Bash 在子 shell 中运行它 - 至少在默认情况下。在 Bourne shell,循环中的赋值将在循环后在主 shell 中可用;在 Bash 中,它们不是。第一个版本总是设置数组变量,因此它可以在循环后使用。)

你也可以使用:

array+=( $line )

添加到数组中。

【讨论】:

    【解决方案2】:

    你可以把命令放在while前面:

    (echo <<EOM
    test1
    test2
    test3
    test4
    EOM
    ) | while read line; do
            array=( ${array[@]} $line )
            echo ${array[@]}
    done
    

    【讨论】:

    • 正如 sha 所说,cat 在这里可能比 echo 更合适。
    【解决方案3】:

    替换

    done < <( echo <<EOM
    

    done < <(cat << EOM
    

    为我工作。

    【讨论】:

      猜你喜欢
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2019-03-02
      • 2015-03-14
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多