congdong007

Penetration Test、Software Developer

0%

Bash Scripting 08 - While Loops

While loops are also fairly common and execute code while an expression is true. While loops have
a simple format and, like if, use the square brackets ([]) for the test:

1
2
3
4
while [ <some test> ]
do
<perform an action>
done

Let’s re-create the previous example with a while loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
kali@kali:~$ cat ./while.sh
#!/bin/bash
# while loop example
counter=1
while [ $counter -lt 10 ]
do
echo "10.11.1.$counter"
((counter++))
done
kali@kali:~$ chmod +x ./while.sh
kali@kali:~$ ./while.sh
10.11.1.1
10.11.1.2
10.11.1.3
10.11.1.4
10.11.1.5
10.11.1.6
10.11.1.7
10.11.1.8
10.11.1.9

This is not the output we expected. This is a common mistake called an “off by one” error. In the
example above, we used -lt (less than) instead of -le (less than or equal to), so our counter only got
to nine, not ten as originally intended.

The ((counter++)) line uses the double-parenthesis (( )) construct to perform arithmetic
expansion and evaluation at the same time. In this particular case, we use it to increase our counter
variable by one. Let’s re-write the while loop and try the example again:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
kali@kali:~$ cat ./while2.sh
#!/bin/bash
# while loop example 2
counter=1
while [ $counter -le 10 ]
do
echo "10.11.1.$counter"
((counter++))
done
kali@kali:~$ chmod +x ./while2.sh
kali@kali:~$ ./while2.sh
10.11.1.1
10.11.1.2
10.11.1.3
10.11.1.4
10.11.1.5
10.11.1.6
10.11.1.7
10.11.1.8
10.11.1.9
10.11.1.10

Our while loop is looking much better now.