在Bash中循环遍历变量中的行,使用while循环。

6
假设有一个名为 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

echo $line 不等同于 echo "$line"。请参见BashPitfalls#14 - Charles Duffy
此外,全大写的变量名用于具有对 shell 或操作系统有意义的变量,而带有小写字符的名称保证不会与系统操作冲突。请参见 http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html 的第四段。 - Charles Duffy
2个回答

6

您有几个选项:

  • A herestring (note that this is a non-POSIX extension): done <<<"$MY_VAR"
  • A heredoc (POSIX-compliant, will work with /bin/sh):

    done <<EOF
    $MY_VAR
    EOF
    
  • A process substitution (also a non-POSIX extension, but using printf rather than echo makes it more predictable across shells that support it; see the APPLICATION USAGE note in the POSIX spec for echo): done < <(printf '%s\n' "$MY_VAR")

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

感谢上面详细的解释和有用的评论。非常感谢。 - Michael Gruenstaeudl

5
< p > < code > < 需要后面跟着一个文件名。您可以使用这里字符串:

done <<< "$MY_VAR"

或进程替换:

done < <(echo "$MY_VAR")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接