Hi all,
a problem with a loop. Imagine it starts with
var1="$(cat txtif.out )"
while [ $var1 = x ]
do
echo file1
echo file2
echo y > txtif.out
if [ $var1 = y ]
then
break
fi
done
exit 0
the problem is that if the file is changing during the loop seems to continue as it reads "x" state, while in the loop it should change to y and break, instead it returns from the beginnig.
What and why should change to "y"? The "control variable" var1 is NOT modified within the loop. So - either the loop is not entered at all, or it will loop forever.
Thanks. Is there a way to modify a control variable within the loop?
Imagine the starting file has x inside. (txtif.out)
i would like to modify it so when, in the loop, i modify the file (ex with echo y) it will read the y and since it is different from x , will break the loop.
If the first line of the file txtif.out is not x followed by a <newline> character, your script will exit without printing anything. Otherwise, you have an infinite loop printing three lines each time through the loop.
If you want to break out of the loop, you either need to change the value of var1 to something other than x inside the loop, or execute a break statement in the loop (which you code cannot do since the value of var1 never changes in your loop).
If something inside your loop is changing the contents of txtif.out (which nothing currently does) or in some external process is changing the contents of txtif.out and you want to the loop to stop when that happens, you would need something more like:
read var1 < txtif.out
while [ "$var1" = x ]
do
echo file1
echo file2
echo y txtif.out
read var1 < txtif.out
done
exit 0
If you think that the command:
echo y txtif.out
would change the contents of txtif.out to the string y ; it does not. And, if you think that changing the contents of txtif.out will affect your infinite loop; it will not. That would be done by:
echo y > txtif.out
but, if you just want to execute a loop once, why have a loop. An if statement would be more appropriate:
read var1 < txtif.out
if [ "$var1" = x ]
then
echo file1
echo file2
echo y txtif.out # or maybe you wanted echo y > txtif.out instead.
fi
exit 0