PDA

View Full Version : Shell variable in Linux is reset after while loop



huangyingw
June 4th, 2010, 04:04 PM
Hello,
I had following code:


#! /bin/bash
check_file=/root/disk_list.txt
result=1
cat $check_file | while read file ; do
result=0
echo ${result}
done
echo ${result}

the variable result is expected to be set to value 0 in while loop, while after the while loop, its value is reset to the original value 1.
While if I use for loop instead of while loop, the curious reset phenomenent would not occur.
Could someone explain this?
What's the difference between for and while loop?

geirha
June 4th, 2010, 04:12 PM
http://mywiki.wooledge.org/BashFAQ/024

huangyingw
June 5th, 2010, 03:53 AM
http://mywiki.wooledge.org/BashFAQ/024

thanks first, I am reading.

gmargo
June 5th, 2010, 02:01 PM
Taking the first suggestion (useless use of cat) from that helpful FAQ, the simplest fix is probably:



#! /bin/bash
check_file=/root/disk_list.txt
result=1
while read file ; do
result=0
echo ${result}
done < $check_file
echo ${result}

huangyingw
June 10th, 2010, 03:54 PM
Taking the first suggestion (useless use of cat) from that helpful FAQ, the simplest fix is probably:



#! /bin/bash
check_file=/root/disk_list.txt
result=1
while read file ; do
result=0
echo ${result}
done < $check_file
echo ${result}

Yes, I have tried this simplest fix, and it works, thank you.