bash 如何在 while 循环中“读取”变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13122441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I "read" a variable on a while loop
提问by Crazy_Bash
How can I read from variable with while read line
?
如何从变量中读取while read line
?
For example:
例如:
the_list=$(..code..)
while read line
do
echo $line
done < $the_list
using the code above gives me error:
使用上面的代码给了我错误:
./copy.sh: line 25: $the_list: ambiguous redirect
回答by ruakh
You can write:
你可以写:
while IFS= read -r line
do
echo "$line"
done <<< "$the_list"
See §3.6.7 "Here Strings" in the Bash Reference Manual.
请参阅Bash 参考手册中的第 3.6.7 节“此处的字符串”。
(I've also taken the liberty of adding some double-quotes, and adding -r
and IFS=
to read
, to avoid too much mucking around with the contents of your variables.)
(我还冒昧地添加了一些双引号,并添加了-r
和IFS=
to read
,以避免过多地处理变量的内容。)
回答by choroba
If you do not use the variable for anything else, you can even do without it:
如果您不将该变量用于其他任何用途,您甚至可以不用它:
while read line ; do
echo $line
done < <( ... code ... )
回答by Useless
You can just use
你可以使用
your_code | while read line;
do
echo $line
done
if you don't mind the while loop executing in a subshell (any variables you modify won't be visible in the parent after the done
).
如果您不介意在子 shell 中执行 while 循环(您修改的任何变量在 之后的父级中都不可见done
)。
回答by Sachin Patel
Script file should be in Linux mode. Previously it was in dos mode. I changed it by using dos2unix filename
.
脚本文件应为 Linux 模式。以前它处于dos模式。我使用 dos2unix filename
.
e.g.:
例如:
dos2unix sshcopy.sh
Now it works for me.
现在它对我有用。