How to Use the for Loop in a Linux Bash Shell Script
A for loop is a type of control structure commonly used in programming languages to perform repetitive tasks. In a Linux Bash shell script, the for loop is used to iterate through a set of values and perform a specific action for each value in the set. This article will provide a simple guide to using the for loop in a Linux Bash shell script.
- Basic syntax
The basic syntax for a for loop in a Linux Bash shell script is as follows:
for variable in value1 value2 value3 … valuen
do
command1
command2
…
commandN
done
In this syntax, the ‘variable’ is a placeholder for the current value being displayed in the loop. ‘Value1’ to ‘valuen’ are the values that the loop will iterate through. ‘Command1’ to ‘CommandN’ are the actions or commands to be performed in each iteration of the loop.
- Iterating through a list of values
One common use of the for loop in a Linux Bash shell script is to iterate through a list of values. This is done by specifying the list of values after the ‘in’ keyword. For example, to iterate through the list of fruits, the script would look like this:
#!/bin/bash
for fruit in apple banana orange
do
echo “I like $fruit”
done
In this script, the loop iterates through the values ‘apple’, ‘banana’, and ‘orange’. For each value, the script executes the command ‘echo “I like $fruit”‘ which prints the message “I like apple”, “I like banana” and “I like orange” respectively.
- Iterating through a range of values
Another use of the for loop in a Linux Bash shell script is to iterate through a range of numerical values. This is done using the ‘seq’ command, which generates a sequence of numbers. For example, to iterate through the numbers 1 to 10, the script would look like this:
#!/bin/bash
for number in $(seq 1 10)
do
echo $number
done
In this script, the loop iterates through the numbers 1 to 10, generating the sequence using the ‘seq’ command. For each number, the command ‘echo $number’ is executed, which prints the number to the console.
- Using the for loop with arrays
Finally, the for loop can also be used to iterate through arrays in a Linux Bash shell script. An array is a collection of values stored in a single variable. Here is an example of how to use the for loop with an array:
#!/bin/bash
fruits=(“apple” “banana” “orange”)
for fruit in “${fruits[@]}”
do
echo “I like $fruit”
done
In this script, the array is defined using the syntax ‘fruits=(“apple” “banana” “orange”)’. The for loop iterates through each value in the array using the ‘@’ symbol and the ‘[]’ brackets: “${fruits[@]}”. For each value, the script executes the command ‘echo “I like $fruit”‘, which prints the message “I like apple”, “I like banana” and “I like orange” respectively.