gpt4 book ai didi

bash - bash中变量的while循环

转载 作者:行者123 更新时间:2023-12-04 01:44:10 25 4
gpt4 key购买 nike

假设一个文件 file多行。

$ cat file
foo
bar
baz

进一步假设我希望用 while 循环遍历每一行。
$ while IFS= read -r line; do
$ echo $line
$ # do stuff
$ done < file
foo
bar
baz

最后,请假设我希望传递存储在变量中的行而不是存储在文件中的行。如何遍历保存为变量的行而不会收到以下错误?
$ MY_VAR=$(cat file)
$ while IFS= read -r line; do
$ echo $line
$ # do stuff
$ done < $(echo "$MY_VAR")
bash: $(echo "$MY_VAR"): ambiguous redirect

最佳答案

您有多种选择:

  • 一个 herestring(注意这是一个非 POSIX 扩展):done <<<"$MY_VAR"
  • 一个 heredoc(符合 POSIX,将与 /bin/sh 一起使用):
    done <<EOF
    $MY_VAR
    EOF
  • 进程替换(也是一个非 POSIX 扩展,但使用 printf 而不是 echo 使得它在支持它的 shell 中更具可预测性;参见 POSIX spec for echo 中的 APPLICATION USAGE 注释): done < <(printf '%s\n' "$MY_VAR")


  • 请注意,前两个选项将(在 bash 中)使用变量的内容在磁盘上创建一个临时文件,而最后一个使用 FIFO。

    关于bash - bash中变量的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44767772/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com