>While Loop_
Loops are an important concept in programming and therefore also in scripting.
Thanks to loops you are able to repeat an instruction
automatically several times, until a certain condition turns false.
Two are the main types of loops: while and for. They both generate a repeating piece of code, but with some key differences that make them suitable for different needs while programming.
While loops take this form: Here is a simple first example: In this first example, you simply create a variable called i and evaluate it to 0. Then you access the while loop: the condition
Here is an example: No termination condition is set for the loop in this example. This type of loop is called an infinite loop.
The
The output of this piece of code is:
Here is an example: The
Two are the main types of loops: while and for. They both generate a repeating piece of code, but with some key differences that make them suitable for different needs while programming.
While loops take this form: Here is a simple first example: In this first example, you simply create a variable called i and evaluate it to 0. Then you access the while loop: the condition
[$i -lt 4]
means that this while
loop will run until the i
variable is less than 4.
Every cycle of this loop, you print out the value of variable i with echo $i
and finally, you increase its value by 1 with i=$((i + 1))
.
Therefore in 4 cycles the value of i will be 4. This will make the condition of the while loop false.
The output of this piece of code is:
0 1 2 3Sometimes it is required to declare infinite loops for various programming purposes.
Here is an example: No termination condition is set for the loop in this example. This type of loop is called an infinite loop.
The
exit
statement is used to quit the loop. This loop will
iterate for 9 times, then
as soon as i
becomes equal to 0, the condition of the last if
statement will evaluate to true and the loop will be terminated. The output of this piece of code is:
1: Hello World 2: Hello World 3: Hello World I love programming 4: Hello World 5: Hello World I love Bash 6: Hello World 7: Hello World I love this website 8: Hello World 9: Hello WorldIf you want your shell to hang forever doing nothing you can write out the following infinite loop: In scripting, while loops are often used to process files line by line.
Here is an example: The
read
command is used to read a file line by line.
The flag -r
is used to tell the
command read to interpret backslashes (/) literally, instead as escape characters.
This command, expect for some few
rare cases, should always be used with this flag.
In this example, < "$file"
redirects the loop's input from a file
whose name is stored in a variable.
This file has 3 columns, first_name last_name phone
, separated by
blank space (or a tab).
This piece of code only prints out the second column.