What Is the Syntax for Different Types of Loops Available in Shell Scripting?

//

Heather Bennett

What Is the Syntax for Different Types of Loops Available in Shell Scripting?

In shell scripting, loops are an essential construct that allows you to repeat a block of code multiple times. They are incredibly powerful tools for automating repetitive tasks and iterating over data sets.

Shell scripting offers different types of loops, each with its own syntax and use cases. Let’s explore the syntax for each type:

1. The for Loop

The for loop is used to iterate over a list of values or elements. It follows the syntax:

for variable in list
do
    # code block to be executed
done

The variable takes on each value from the list, and the code block is executed until all values have been processed.

Example:

fruits=("apple" "banana" "cherry")

for fruit in "${fruits[@]}"
do
    echo "I like $fruit"
done

This will output:

  • I like apple
  • I like banana
  • I like cherry

2. The while Loop

The while loop repeats a code block as long as a specific condition is true. Its syntax is as follows:

while [ condition ]
do
    # code block to be executed
done

The condition can be any expression that evaluates to either true or false.

count=1

while [ $count -le 5 ]
do
    echo "Count: $count"
    count=$((count + 1))
done
  • Count: 1
  • Count: 2
  • Count: 3
  • Count: 4
  • Count: 5

3. The until Loop

The until loop is similar to the while loop but continues executing the code block until a specific condition becomes true. Its syntax is:

until [ condition ]
do
    # code block to be executed
done

The code block keeps executing as long as the condition evaluates to false.

number=10

until [ $number -eq 0 ]
do
    echo "Number: $number"
    number=$((number - 1))
done
  • Number: 10
  • Number: 9
  • .
    .

In Conclusion

You now have a solid understanding of the syntax for different types of loops available in shell scripting. The for loop is ideal for iterating over a list, while the while and until loops are perfect for executing code based on specific conditions. By utilizing these loops effectively, you can streamline your shell scripts and automate repetitive tasks with ease.

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy