如何在while循环中"读取"变量

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".

(我也考虑加入一些双引号,并加入的自由-rIFS=read,避免过多与变量的内容围绕搞混.)

  • @doubleDown:`IFS =`将`$ IFS`设置为空字符串(因此它根本不包含任何字符).在这种情况下,由于只有一个字段,其唯一的作用是防止从行的开头删除前导IFS字符.(看看我的意思,比较`read foo <<<'bar'; echo"$ foo"`和`IFS = read foo <<<'bar'; echo"$ foo"`.) (6认同)
  • `IFS =`是否将IFS设置为null字符?在这种情况下你为什么需要它? (2认同)

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).