Cra*_*ash 38 variables bash while-loop
我如何从变量中读取while read line?
例如:
the_list=$(..code..)
while read line
do
echo $line
done < $the_list
Run Code Online (Sandbox Code Playgroud)
使用上面的代码给我错误:
./copy.sh: line 25: $the_list: ambiguous redirect
Run Code Online (Sandbox Code Playgroud)
rua*_*akh 60
你可以写:
while IFS= read -r line
do
echo "$line"
done <<< "$the_list"
Run Code Online (Sandbox Code Playgroud)
请参阅Bash参考手册中的§3.6.7"Here Strings".
(我也考虑加入一些双引号,并加入的自由-r和IFS=对read,避免过多与变量的内容围绕搞混.)
cho*_*oba 24
如果您不将该变量用于其他任何事情,您甚至可以不使用它:
while read line ; do
echo $line
done < <( ... code ... )
Run Code Online (Sandbox Code Playgroud)
Use*_*ess 20
你可以使用
your_code | while read line;
do
echo $line
done
Run Code Online (Sandbox Code Playgroud)
如果你不介意在子shell中执行while循环(你修改的任何变量在后面的父级中都不可见done).