Computer scienceSystem administration and DevOpsCommand lineBash syntax

Loops and sequences

11 minutes read

Loops in programming are a handy concept that allows iterating the same function or method over a set of values. This is relatively easy to do and greatly helps with repetitive tasks. Loops in Bash are even more helpful. The set of values that you define could be anything that bash can extrapolate to a list. This property of bash loops makes them relatively flexible and easy to understand.

For loops are the most common type, so let's start with them.

For loop

The for loop in Bash iterates a command over a set of values. The syntax is the following:

for variable in set_of_values
do
    command
done

This code basically means that the commands between do and done will be iterated over a set of values. The values that specify the number of times our loop will iterate will be contained in the variable. Here's an example of how it looks in the terminal:

$ for i in 1 2 3 4 5 do 
    echo $i 
  done
1
2
3
4
5

In this code, we use the echo command to display the set of numbers we entered. To set up the values, you can also use ranges. The syntax is the following:

for i in {n..N}
do
    command
done

When you use ranges, it is enough to just define the start (n) and the end (N) of your set of values. By default, it will iterate through your set with a step of 1. However, you can change the step parameter. Here's an example of a range from 1 to 5 with a step of 2 in the terminal:

$ for i in {1..5..2} do 
    echo $i
  done
1
3
5

Parameters of a for loop can be even more flexible. It's not necessarily numbers: for example, you can iterate a list of strings:

$ for i in John Jack Mary do 
    echo "Here is $i" 
  done
Here is John
Here is Jack
Here is Mary

Using the seq command in a for loop

To iterate a range of numbers, you can use the seq command. In this command, sequences can be generated using the following syntax:

seq [options] number

When the seq command is written with only one number, the sequence will start from 1 with a step of 1 and end at the given number:

$ seq 4
1
2
3
4

This command may also have a few options:

  • -f this option is used to format the output in a particular way. You can use format description operators to set the format. By default, it's %g. To adjust the format option, you just need to use the format operator: seq -f %f 5.

  • -w – this option is used to set an equal width for the whole sequence by padding numbers with leading zeros.

  • -s – this option is used to separate the numbers with a string. By default, the string is set to "\n". If you, for example, use the string " | ", the sequence will look like this:

$ seq -s " | " 5
1 | 2 | 3 | 4 | 5

You can use the seq command to generate an arithmetic progression using the following syntax:

seq [start] [incr] [stop]

Here, start is the first number of a sequence, stop is its last number, and incr is the increment step. Numbers in a sequence can be both positive and negative, and the sequence can go in both directions.

The seq command can be used as a range for a for loop. To do this, you can use the following syntax:

for i in $(seq command)
do
    command
done

Here's an example of a loop that goes from 1 to 5 with a step of 2:

$ for i in $(seq 1 2 5); do 
    echo "Number: $i"
  done
Number: 1
Number: 3
Number: 5

While loop

The while loop is a construct that will be executed as long as a control command returns the true status. The control command is any command that can return the true or false status. In its simplest form, it could be a condition for the loop to run. The condition for a loop has to be separated by brackets. The syntax for a condition loop is as follows:

while [ condition ]
do
    command
done

If you are using some other command or calling a function, you shouldn't use brackets:

while control-command
do
    command
done

Here's an example of a loop that will go on while the variable i is less than or equal to 3:

$ i=1
$ while [ $i -le 3 ] do 
    echo "I is $i" 
    i=$(($i+1)) 
  done
I is 1
I is 2
I is 3

There is also an until loop, which is the opposite of a while loop, meaning that your loop will be executed until your control command returns the true status (or while it returns false).

If you use only true as the condition for a loop, you'll initiate an endless loop. In the terminal, it will look like this:

$ while true; do
    echo "To stop execution of a loop, use CTRL+C"
  done

In real life, you don't want to loop forever, so it might seem useless. However, infinite loops can be manipulated with conditional statements.

Conditional loop control

Loops can be conditionally controlled with the break and continue commands inside an if statement. The statement will include the command then, which executes commands if the condition returns true, and fi, which executes commands if the condition returns false. If statements can be used in all three loops. The syntax is as follows:

for i in set_of_values
do
    if [ condition ]
    then
        break # or continue
    fi
    command
done

The break command allows us to initiate an early exit from the loop. Here's an example of a loop containing 5 numbers, which will exit on the 4th number:

$ for i in $(seq 1 5); do 
    if [ $i -eq 4 ]; then 
        break; 
    fi
    echo "Number: $i" 
  done
Number: 1
Number: 2
Number: 3

Using continue allows us to skip some iterations of a loop without exiting it. Here's an example of a loop that goes from 1 to 10 skipping the numbers greater than 5 and less than 10:

$ for i in $(seq 1 10); do 
    if [ $i -gt 5 ] && [ $i -lt 10 ]; then 
        continue; 
    fi; 
        echo "Number: $i" 
  done
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 10

Conclusion

Bash loops could be used in different ways to execute repetitive tasks. It's a useful tool with a lot of options that may come in handy for simple coding tasks.

113 learners liked this piece of theory. 2 didn't like it. What about you?
Report a typo