This article will introduce how to loop with for
or while
in Bash
1. while Loop
This is the syntax for a while
loop. The loop will repeat as long as the condition is True, and will end when the condition is False.
while [ condition ]
do
Statements
done
This is an example of a while loop that prints from 1 to 5.
The condition of the loop, [ "$a" -lt 5 ]
, means $a < 5
. And $(expr $a + 1)
means an operation that adds 1 to $a
.
#!/bin/bash
a=0
while [ "$a" -lt 5 ]
do
a=$(expr $a + 1)
echo $a
done
Output:
$ bash example.sh
1
2
3
4
5
2. while Loop (Infinite loop)
In the code below, the :
next to the while means True, so the loop will repeat infinitely. You can terminate the program with Ctrl + C
.
#!/bin/bash
while :
do
echo "Please type something in (^C to quit)"
read INPUT_STRING
echo "You typed: $INPUT_STRING"
done
$ bash example.sh
Please type something in (^C to quit)
aaa
You typed: aaa
Please type something in (^C to quit)
bbb
You typed: bbb
Please type something in (^C to quit)
^C
3. for Loop
This is the syntax for a for loop. The for loop will repeat for the number of variables inputted after the in
.
Each time the loop is repeated, the variable var
will be assigned to wordN
.
for var in word1 word2 ... wordN
do
Statements
done
If you look at the example below, you can easily understand how a for loop works.
#!/bin/bash
for var in 1 2 3 4 5
do
echo $var
done
Output:
$ bash example.sh
1
2
3
4
5
And after in
, characters other than numbers are also possible.
#!/bin/bash
for var in 1 2 a 4 HELLO
do
echo $var
done
Output:
$ bash example.sh
1
2
a
4
HELLO
4. until Loop
The following is the syntax for an until loop. The loop will repeat until the condition is False, and will end when the condition is True.
Until is the same as while, except that the condition is reversed. That is, until [ ! condition ]
will work the same as while [ condition ]
.
until [ condition ]
do
Statements
done
Here is an example of using an until loop to print 1-5.
In the code, [ $a -ge 5 ]
means $a >= 5
, i.e. the loop will repeat until $a
becomes 5.
#!/bin/bash
a=0
until [ $a -ge 5 ]
do
a=$(expr $a + 1)
echo $a
done
Output:
$ bash example.sh
1
2
3
4
5
Related Posts
- How to measure elapsed time in Bash
- Ceil, Floor, Round off a devided number in Bash
- Check if a number is Positive or Negative in Bash
- How to Print a Variable in Bash
- Number Comparison Operators in Bash
- Convert between Uppercase and Lowercase in Bash
- Check if a File or Directory exists in Bash
- How to extract substring in Bash
- Bash Case Statement with examples
- How to use Command Line Arguments in Bash
- How to use Arrays in Bash
- How to Compare strings in Bash Shell
- if..else statement in Bash
- Add, Subtract, Multiply, Division with Numbers in Bash
- Bash For, Whlie Loop Examples
- How to Pass and Use command line arguments in Bash