问题描述
假设一个文件 file
有多行.
Assume a file file
with multiple lines.
$ cat file
foo
bar
baz
进一步假设我希望用 while 循环遍历每一行.
Assume further that I wish to loop through each line with a while-loop.
$ while IFS= read -r line; do
$ echo $line
$ # do stuff
$ done < file
foo
bar
baz
最后,请假设我希望传递存储在变量中的行而不是存储在文件中的行.如何遍历保存为变量的行而不收到以下错误?
Finally, please assume that I wish to pass lines stored in a variable rather than lines stored in a file. How can I loop through lines that are saved as a variable without receiving the below error?
$ MY_VAR=$(cat file)
$ while IFS= read -r line; do
$ echo $line
$ # do stuff
$ done < $(echo "$MY_VAR")
bash: $(echo "$MY_VAR"): ambiguous redirect
推荐答案
您有几个选择:
- 此处字符串(请注意,这是一个非 POSIX 扩展):
done <<<"$MY_VAR"
一个 heredoc(符合 POSIX,将与
/bin/sh
一起使用):
done <<EOF
$MY_VAR
EOF
一个进程替换(也是一个非 POSIX 扩展,但使用 printf
而不是 echo
使它在支持它的 shell 中更具可预测性;请参阅 APPLICATIONecho
的 POSIX 规范): done
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.
Note that the first two options will (in bash) create a temporary file on disk with the variable's contents, whereas the last one uses a FIFO.
这篇关于bash中变量的while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!