日期:2014-05-16  浏览次数:20896 次

bash如何把while循环的变量传出来
举个例子:

test=1
while xxx
do
    test=2
done
echo $test

结果输出test的值为1,如何才能把循环中的变量传出来?
------解决方案--------------------
test=1
i=0
while [ "$i" == 0 ]
do
    test=2
    let i+=1
done
echo $test

这样没有问题。
如果你在while前面使用了管道,请把真实代码贴出来,我帮你改。
------解决方案--------------------
相认你能看懂下面的意思:

linux:~ # cat a.sh
#!/bin/sh

test=1
cat /etc/passwd 
------解决方案--------------------
 while read line
do
    test=2
done 
echo $test

linux:~ # sh a.sh
1
linux:~ # cat b.sh
#!/bin/sh

test=1
while read line
do
    test=2
done  < /etc/passwd

echo $test

linux:~ # sh b.sh
2
linux:~ # 
------解决方案--------------------
$ total_num=1
$ while read line;do ((total_num++));done < <(cat /etc/passwd)
$ echo $total_num
40