loop statment in bash or shell script

Loop statement in bash or shell script

Loop statement in bash or shell script

loop in bash, if ever we want to do some task repeatedly then we use loop statement in bash script.

We have following loop in bash script

for loop
while loop
until loop

for loop in bash

for value in parameter1 parameter2 parameter3
do
Statements or commands
done

Example

Also we can use below syntax

for arg in [list]
do
command(s)
done

If do is on same line as for, there needs to be a semicolon after list.

for arg in [list] ; do
command(s)
done

Bash for loop range

example

output

Bonus Example

From below script we will fetch all the users on the system

Output

Bash while loop

Bash while loop first  tests for a condition at the top of a loop, and keeps looping as long as that condition is true (returns a 0 exit status).

syntax

while [ Check for condition ]
do
Statements or commands
done

OR

Its always required semicolon while we use do keywords  on the same line with while keywords

while [ condition ] ; do
Statement
done

Simple while loop Example

Output

Bash Until loop

Until loop tests for a condition at the top of a loop, and keeps looping as long as that condition is false (opposite of while loop).

until [ condition-is-true ]
do
Statements
done

OR

until [ condition-is-true ] ; do
Statements
done

Example of Until loop

Output

Break, Continue in bash script

The break command terminates the loop (breaks out of it), while continue causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle.


You May Also Enjoy Reading This …

Leave a Reply

Your email address will not be published. Required fields are marked *