Bash Shell ScriptingOne of the earliest programming challenges that I was presented with was very simple: add all the numbers from one to fifty.

The problem that I had with this challenge was also very simple; I wasn’t allowed to use a calculator, or paper, or even to solve it in my head.

I was supposed to write a program that did the math for me.

At that time — I was thirteen, and seemingly clueless about logic — it seemed insurmountable. I eventually gave up.

Two years later I tried again, and that time I had a Eureka! moment when I learned about loops. Suddenly I wondered why it had ever even sounded hard. Ah, hindsight!

Loops are used to run and re-run a block of code, again and again, until a condition is met; they “loop” around in a full circle, to start all over again, until the cycle is broken.

There are several different loop structures that can be used; they are similar, yet different enough to each be ideal for a unique situation.

The WHILE Loop

The while loop is a simple one to figure out, just by using its name as the basis of understanding.

A while loop will continue looping while a condition or test continues to be true. Once the condition/test is found to be false, the loop will end.

The while loop syntax is:

while [ test(s) ]
do
    action(s) to perform
done

An example of the while loop in action (ironically, solving the first challenge I was presented with) is:

#!/bin/bash
total=0
num=1
while [ $num -le 50 ]
do
    total=$(($total + $num))
    ((num++))
done
echo $total
exit 0

The UNTIL Loop

The until loop is another control structure whose function is made simple by its name.

An until loop will continue looping until a condition or test is met, or while the condition/test is still false.

The until loop syntax is:

until [ test(s) ]
do
    action(s) to perform
done

An example of the until loop in action is:

#!/bin/bash
total=0
num=1
until [ $num -eq 51 ]
do
    total=$(($total + $num))
    ((num++))
done
echo $total
exit 0

The FOR Loop

The for loop will repeat a block of code for each item in a list.

A list is, in this instance, a number of strings, separated by spaces. Example: food=’rice oats barley wheat corn’

The for loop syntax is:

for var in list
do
    action(s) to perform
done

Each list item is assigned to var (a place-holding-variable), one at a time and in chronological order, to be run through the loop so that actions can be performed based on that value.

An example of the for loop in action is:

#!/bin/bash
for pets in Dogs Cats Hamsters Snakes Hedgehogs Spiders Chinchillas
do
    echo $pets are commonly kept as pets.
done
exit 0

Another for loop example, making use of a range of numbers (enclosed in curly braces) is:

#!/bin/bash
total=0
for num in {1..50}
do
    total=$(($total + $num))
done
echo $total
exit 0

The SELECT Loop

The select loop creates a numbered menu, from which users can select options.

The select loop syntax is very similar to a for loop:

select var in list
do
    action(s) to perform
done

To summarize the syntax, simply specify a variable that the selected result(s) will be stored in, then specify the listed items (space-separated).

Actions to be performed based on the results should be on separate lines between the “do” and “done” lines.

Enclosing if statements and/or case statements in a select loop is a good way to handle the results.

Note: The select loop “prompt” is stored in the PS3 system variable, so re-define this variable to customize the prompt.

A working example of the select loop might look something like this:

#!/bin/bash
options='start restart stop pause continue quit'
PS3='Select An Option: '
select opt in $options
do
    if [ $opt == 'quit' ]; then
        break
    fi
    echo You chose to ${opt}.
done
exit 0

Conclusion

Now that you know about loops, the earlier mentions of control commands such as break, exit, and continue, should make more sense. They are often used in loops to break out before conditions turn false, etc.

Try out the example scripts to see how each one works, and make modifications as necessary to complete tasks in your command line.

As usual, plotting out your needs in advance will allow you to determine which loop is best suited to meet them.

Next, we’ll discuss the creation and utilization of user-defined functions, before closing out our bash shell scripting series with a cheat sheet.