Bash Script for Loop

  • Read
  • Discuss

The for loop in a bash script is used to repeatedly execute a set of commands for a specified list of items. The basic syntax for a for loop is:

for variable in list; do
  commands
done

Let’s look at a practical example.

  1. Open your terminal or shell.
  2. Create a new file using a text editor of your choice. For example, you can use the nano editor to create a file called “forloop.sh”:
nano forloop.sh
  1. Type the following code into the file:
#!/bin/bash

# Defining an array
colors=("red" "green" "blue")

# Using the for loop to iterate over an array
for color in "${colors[@]}"; do
  echo "The color is $color"
done
  1. Save the file and exit the editor.
  2. Make the file executable by running the following command in the terminal:
#!/bin/bash

# Defining an array
colors=("red" "green" "blue")

# Using the for loop to iterate over an array
for color in "${colors[@]}"; do
  echo "The color is $color"
done

chmod +x forloop.sh

./forloop.sh
  1. Finally, run the script by typing:

You should see the following messages printed in the terminal:

The color is red
The color is green
The color is blue

And that’s it! This is a simple example of how to use the for loop in a Bash script.

Leave a Reply

Scroll to Top