嵌套循环

时间:2017-10-06 13:37:22

标签: bash while-loop

我有一个bash代码:

var="empty"

find $path1 -maxdepth 3  | while read line; do
find $path2 -maxdepth 1  | while read line2; do        
    if [[ $line2 != $var ]]; then
      echo "new value"
    fi
    var=$line2
 done <<< "$line2"
done

问题是......如何让var保持不变?因为我想回应循环找到的每个新值,但它不起作用;(var="empty"每次第二个循环开始迭代时。

如何为每次迭代制作var=$line2

1 个答案:

答案 0 :(得分:-1)

您正在使用stdin读取将值读入line2,并将第2行的值传递到done的循环中,并在stdin上使用here-string。 bash给出了here-string优先级,所以line2只是从line2分配,这意味着它永远不会被设置。

echo -e "one\nthree\nfive" | while read num
do echo $num
done <<< "two"  

输出为two。输入流完全被忽略。

您也无缘无故地定义嵌套循环,因为您从不使用外循环。请在发布之前清理您的代码。

find ~ | while read f; do var=$f; echo $f; done

这很好用。