Sams Teach Yourself Shell Programming in 24 Hours
(Publisher: Macmillan Computer Publishing)
Author(s): Sriranga Veeraraghavan
ISBN: 0672314819
Publication Date: 01/01/99
Summary
Loops are a powerful programming tool that enable you to execute a set of commands repeatedly. In this chapter, you have examined the following types of loops available to shell programmers:
- while
- until
- for
- select
You have also examined the concept of nested loops, infinite loops, and loop control. In the next chapter, Ill introduce the concept of parameters. Here youll see one of the most common applications of loops.
Questions
- 1. What changes are required to the following while loop
x=0
while [ $x -lt 10 ]
do
echo "$x \c"
y=$(($x-1))
x=$(($x+1))
while [ $y ge 0 ] ; do
y=$(($y-1))
echo "$y \c"
done
echo
done
so that the output looks like the following:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
- 2. Write a select loop that lists each file in the current directory and enables the user to view the file by selecting its number. In addition to listing each file, use the string Exit Program as the key to exit the loop. If the user selects an item that is not a regular file, the program should identify the problem. If no input is given, the menu should be redisplayed.
Terms
- Loops
- Loops enable you to execute a series of commands multiple times. Two main types of loops are the while and for loops.
- Body
- The set of commands executed by a loop.
- Iteration
- A single execution of the body of a loop.
- Nested Loops
- When a loop is located inside the body of another loop it is said to be nested within another loop.
- Infinite Loops
- Loops that execute forever without terminating.