CyberArmy University | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Services & Projects

[Programming] Shell Programming Series(XI)


[Reply] [View by Thread] [Help]
[Back To Article Discussion Forum]

Posted by Author System On 2007-04-29 10:01:47




View and vote on the article here: Shell Programming Series(XI)


Shell Programming Series(XI)

Category
Programming
Summary
Sometimes, you might want to break out of a loop before the condition necessary to exit the loop has occurred. There are two statements that can be used to break a loop. The first is the <TT>break</TT> statement. The second is the <TT>co
Body
The <TT>break</TT> Statement

The <TT>break</TT> statement will terminate a loop immediately when it is encountered, whether or not the condition required to exit the loop has been met. Following shows a slight modification to the previous program which was repeating the loop indefinitely:

1. #!/bin/sh
2. # Loops indefinitely.
3. while true
4. do
5. echo ?This line will print forever? But??
6. break
7. done
8. echo
9. echo ?The break statement in the loop causes the?
10.echo ?loop to terminate immediately and go the?
11.echo ?first statement after the loop.?
12.exit 0


And the output of this program:

This line will print forever? But?

The break statement in the loop causes the
loop to terminate immediately and go the
first statement after the loop.
bash$


The <TT>continue</TT> Statement

The <TT>continue</TT> statement causes the loop to immediately jump back to the top and re-evaluate the test condition. Any remaining statements in the loop are not executed. Following is another example that uses the endless loop program with a slight modification:

1. #!/bin/sh
2. # Loops indefinitely.
3. while true
4. do
5. echo ?This line will print forever.?
6. continue
7. echo ?But this line will never print even though it is?
8. echo ?inside the loop because the preceding?
9. echo ?continue statement causes the loop to?
10. echo ?jump back to the top and re-evaluate
11. echo "the test.?
12. done
13. echo ?This line will never print since the program?
13. echo ?will never get past the loop?
14. exit 0


This program will indefinitely output ?This line will print forever.? The rest of the <TT>echo</TT> statements inside the loop will never be printed because the <TT>continue</TT> statement before them causes the loop to immediately jump back to the top and re-evalute the test condition.


This article was imported from zZine. (original author: ismail)


There are no replies to this post yet.



Guest:
Subject:
Message:
Signature:
Optional Image Link:
http://

CyberArmy::Forum v0.6
Generated In 0.01389 seconds


About Us | Privacy Policy | Mission Statement | Help