問題描述
skrip shell: loop bersarang dan lanjutkan (shell script : nested loop and continue)
while [condition]
do
for [condition]
do
if [ "$x" > 3 ];then
break
fi
done
if [ "$x" > 3 ];then
continue
fi
done
In the above script I have to test "$x" > 3
twice. Actually the first time I test it, if it is true I want to escape the while loop and continue to the next while loop.
Is there any simpler way so I can use something like continue 2
to escape the outer loop?
‑‑‑‑‑
參考解法
方法 1:
"break" and "continue" are close relatives of "goto" and should generally be avoided as they introduce some nameless condition that causes a leap in the control flow of your program. If a condition exists that makes it necessary to jump to some other part of your program, the next person to read it will thank you for giving that condition a name so they don't have to figure it out!
In your case, your script can be written more succinctly as:
dataInRange=1
while [condition ‑a $dataInRange]
do
for [condition ‑a $dataInRange]
do
if [ "$x" > 3 ];then
dataInRange=0
fi
done
done
(by user1769686、Ed Morton)