Home Linux Loops in Shell Scripting

Loops in Shell Scripting

by Anup Maurya
47 minutes read

Loops are an essential part of shell scripting, which allows you to perform repetitive tasks with minimal effort. Shell scripting loops can be used to execute a set of commands repeatedly until a certain condition is met. In this tutorial, we will discuss different types of loops in shell scripting with examples.

While loop

A while loop executes a set of commands repeatedly as long as a condition is true. The syntax for a while loop in shell scripting is as follows:

while [ condition ]
do
  #commands to be executed
done

Example:

#!/bin/bash
n=1
while [ $n -le 5 ]
do
  echo "Number: $n"
  n=$((n+1))
done

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

For loop

A for loop executes a set of commands for a fixed number of times. The syntax for a for loop in shell scripting is as follows:

for variable in [ list ]
do
  #commands to be executed
done

Example:

#!/bin/bash
for color in red green blue
do
  echo "Color: $color"
done

Output:

Color: red
Color: green
Color: blue

Until loop

An until loop is similar to a while loop, but it executes a set of commands repeatedly until a condition is false. The syntax for an until loop in shell scripting is as follows:

until [ condition ]
do
  #commands to be executed
done

Example:

#!/bin/bash
n=1
until [ $n -ge 5 ]
do
  echo "Number: $n"
  n=$((n+1))
done

Output:

Number: 1
Number: 2
Number: 3
Number: 4

Nested loop

A nested loop is a loop inside another loop. It is useful when you want to perform a task repeatedly for each item in a list. The syntax for a nested loop in shell scripting is as follows:

for variable1 in [ list1 ]
do
  for variable2 in [ list2 ]
  do
    #commands to be executed
  done
done

Example:

#!/bin/bash
for color in red green blue
do
  for number in 1 2 3
  do
    echo "Color: $color, Number: $number"
  done
done

Output:

Color: red, Number: 1
Color: red, Number: 2
Color: red, Number: 3
Color: green, Number: 1
Color: green, Number: 2
Color: green, Number: 3
Color: blue, Number: 1
Color: blue, Number: 2
Color: blue, Number: 3

In conclusion, loops are a fundamental aspect of shell scripting that can help automate repetitive tasks. You can use different types of loops in shell scripting depending on your requirements. Hopefully, this tutorial will help you get started with shell scripting loops.

related posts

Leave a Comment

Enable Notifications OK No thanks