What Are the Three Types of Loops in Bash Scripting?

//

Scott Campbell

Bash scripting is a powerful tool that allows you to automate tasks and improve efficiency in your workflow. One of the key features of bash scripting is its ability to use loops. Loops enable you to repeat a certain block of code multiple times, making your scripts more dynamic and flexible.

Types of Loops in Bash Scripting

In bash scripting, there are three main types of loops that you can utilize:

1. For Loop

The for loop is used when you want to iterate over a list of items or perform a specific action for a defined number of times. It follows the syntax:


for variable in list
do
    # Code to be executed
done

Here, the variable takes on each value from the list, and the code inside the loop is executed for each value.

An example of using a for loop in bash scripting:


fruits=("Apple" "Banana" "Orange")

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

This will output:

  • I love Apple
  • I love Banana
  • I love Orange

2. While Loop

The while loop is used when you want to repeatedly execute a block of code as long as a certain condition is true. It follows the syntax:


while condition
do
    # Code to be executed
done

In this loop, the condition is checked before each iteration. If it evaluates to true, the code inside the loop is executed. Once the condition becomes false, the loop terminates.

An example of using a while loop in bash scripting:


count=1

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

This will output:

  • Count: 1
  • Count: 2
  • Count: 3
  • Count: 4
  • Count: 5

3. Until Loop

The until loop is similar to the while loop but executes the code block until a certain condition becomes true. It follows the syntax:


until condition
do
    # Code to be executed
done

In this loop, the code block is executed as long as the condition evaluates to false. Once it becomes true, the loop terminates.

An example of using an until loop in bash scripting:

until [ $count -gt 5 ]
do
echo “Count: $count”
count=$((count + 1))
done

Conclusion

Loops are essential in bash scripting as they allow you to automate repetitive tasks and iterate over lists of items. The for loop, while loop, and until loop each serve different purposes and can be used based on specific requirements. By incorporating loops into your bash scripts, you can enhance their functionality and make them more efficient.

Remember to experiment with different loop types and explore their capabilities to fully leverage the power of bash scripting!

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

Privacy Policy