Normally in a shell script it is desirable to do something repetitive.
I have touched on some loops in other posts but now would like to go over them in a bit more detail. Each of the examples in this post are intended to give an introduction to looping in bash.
For loops allow you to repeat a section of code a number of times. Its very similar to other languages syntax but works a little differently. The for loop in bash only allows you to give a fixed list of values to loop over. A good way to remember how a for loop works is “For each of the dishes: clean and dry.”
for i [in list]
statements [use $i]
for x in 1 2 3
echo “Number: $x”
This is a very simple script that just counts to 3 and then prints “Finished!”
While and until Loops
In essence while and until are the same in bash. The titles are pretty much self explanatory. A while loop would be explained in real life as “While the sink is still full: wash dishes” and a until loop would be “Until the sink is empty: Wash dishes.”
While and Until Syntax:
until/while [condition] do
Example of a While loop:
while [ $count -lt 10 ]; do
Basically this loop will loop over the code while the count variable is less than 10. If we didn’t put the let statement in the script it would get stuck in the loop causing the user to press CTRL+C to end the script.
Doing the same thing can be done in a until loop except the condition has to be modified to get the same result.
until [ $count -gt 9 ]; do
Now that you’ve figured out how to loop over something its probably a good idea to know how to stop the loop.
All that needs to be done to stop a loop is:
for x in 1 2 3 4 5
if [ $x = 3 ]; then
echo “Number is 3. Quitting”
echo “Number: $x”
This is a very easy to follow example. Its the same as the basic for loop except that if x is 3 it will stop the loop. This example has no real practical purpose. Since its a for loop the number 3 could just have been omitted.
Real World For Loop Example
Looping over all files in /etc and printing all of those that match “grep conf” and putting them in quotes.
The code to do this in a loop is:
for x in $(ls /etc -1|grep conf);
The situation for many bash scripts is that there is normally a shorter way to do something. Take the Real World For Loop Example in this tutorial the same results can be achieved with:
x=$(ls /etc |grep conf); echo “$x”\n
This will get the job done but a loop may be better for esthetic purposes or for additional logic.