Last Updated on June 27, 2023 by Prepbytes
In this blog, we will explore the utilization of the Bash scripts for loop. Similar to other programming languages, Bash shell scripting offers support for ‘for loops’ to accomplish iterative tasks. It allows us to iterate through a specific set of statements across a range of words in a string or elements in an array.
What are Bash Scripts for Loop?
The Bash script for loop allows you to execute a set of statements repeatedly, iterating over a list of values. The general syntax of the for loop in Bash is as follows:
Syntax of Bash Scripts for Loop
for variable in list
do
# Statements to be executed
done
Explanation:
Here’s a breakdown of each component:
for: Keyword indicating the start of the for loop.
variable: A variable that takes the value of each item in the list during each iteration of the loop.
in: Keyword separating the variable and the list.
list: A collection of values over which the loop iterates. It can be a series of words in a string, elements in an array, or a sequence generated using a range.
do: Keyword indicating the beginning of the loop’s block of statements.
# Statements to be executed: Placeholder for the actual code that will be executed during each iteration.
done: Keyword indicating the end of the loop.
Basic For Loop Example of Bash Script
Here’s an example of a Bash script for loop that iterates over a range of numbers and prints each value:
for i in {1..5}
do
echo "Number: $i"
done
In this example, the loop will iterate from 1 to 5, and for each iteration, it will print the value of the variable i.
Example of For Loop to Read a Range in Bash Script
Here’s an example of a Bash script for loop that reads a range of numbers and performs a specific action for each value:
#!/bin/bash
# Read a range of numbers from the user
read -p "Enter the start value: " start
read -p "Enter the end value: " end
# Iterate over the range of numbers
for (( i = start; i <= end; i++ ))
do
echo "Number: $i"
# Perform additional actions with each number
done
In this script, the user is prompted to enter the start and end values of the range. The for loop then iterates from the start value to the end value, inclusively. For each iteration, it prints the current number using the echo command. You can modify the loop body to perform additional actions with each number as needed.
Note: The double parentheses (( )) are used for arithmetic operations within the for loop, allowing us to increment the variable i using i++.
Example of For Loop to Read a Range with Increment/Decrement in Bash Script
Here's an example of a Bash script for loop that reads a range of numbers with a specified increment or decrement:
#!/bin/bash
# Read the start, end, and step values from the user
read -p "Enter the start value: " start
read -p "Enter the end value: " end
read -p "Enter the step value: " step
# Iterate over the range of numbers with the specified step
if (( start <= end )); then
for (( i = start; i <= end; i += step ))
do
echo "Number: $i"
# Perform additional actions with each number
done
else
for (( i = start; i >= end; i -= step ))
do
echo "Number: $i"
# Perform additional actions with each number
done
fi
Explanation
In this script, the user is prompted to enter the start value, end value, and step value for the range. The script then checks whether the start value is less than or equal to the end value. If it is, the for loop iterates from the start value to the end value, incrementing the variable i by the specified step value on each iteration. If the start value is greater than the end value, the for loop iterates in a decrementing manner using the specified step value.
For each iteration, the script prints the current number using the echo command. You can modify the loop body to perform additional actions with each number as needed.
Example of For Loop to Read White Spaces in String as Word Separators in Bash Script
Here's an example of a Bash script for loop that reads white spaces as word separators in a string:
#!/bin/bash
# Read the input string from the user
read -p "Enter a string with white spaces: " input_string
# Set the internal field separator (IFS) to white space
IFS=' '
# Read each word in the input string using a for loop
for word in $input_string
do
echo "Word: $word"
# Perform additional actions with each word
done
Explanation
In this script, the user is prompted to enter a string that contains white spaces. The internal field separator (IFS) is set to a white space character using IFS=' '. This setting allows the for loop to treat white spaces as word separators when reading the input string.
The for loop iterates over each word in the input string, where word is the variable that stores the current word during each iteration. The script then prints each word using the echo command. You can modify the loop body to perform additional actions with each word as needed.
Note: By default, the for loop in Bash splits the input string based on whitespace and treats each word as a separate iteration.
Example of For Loop to Read each line in String as a word in Bash Script
To read each line in a string as a word using a for loop in a Bash script, you can use a combination of the printf command and command substitution. Here's an example:
#!/bin/bash
# Read the input string from the user
read -p "Enter a string with line breaks: " input_string
# Use printf to replace line breaks with spaces
formatted_string=$(printf "%s " "$input_string")
# Read each word in the formatted string using a for loop
for word in $formatted_string
do
echo "Word: $word"
# Perform additional actions with each word
done
Explanation
In this script, the user is prompted to enter a string that may contain line breaks. The printf command is used to replace each line break with a space, resulting in a formatted string where each line is treated as a word. The formatted string is stored in the variable formatted_string using command substitution ($(...)).
The for loop then iterates over each word in the formatted string, where word is the variable that stores the current word during each iteration. The script prints each word using the echo command. You can modify the loop body to perform additional actions with each word as needed.
Note: The printf command with the format "%s " replaces each line break with a space. If you need a different separator or need to handle different formatting scenarios, you can modify the printf command accordingly.
Conclusion
In Bash scripting, the for loop is a powerful construct that allows you to iterate over a list of values and perform repetitive tasks. By defining a loop variable and a list of values, you can execute a set of statements for each value in the list. The for loop is flexible and can be customized to suit various scenarios, making it a fundamental tool in Bash scripting.
Frequently Asked Questions (FAQs) related to Bash script for loop:
Q1. What can be used as a list in the for loop?
The list in a Bash for loop can be a series of words in a string, elements in an array, or a sequence generated using a range.
Q2. Can I specify a step value for iterating in a for loop?
Yes, you can specify a step value for iterating in a for loop. By using arithmetic operations on the loop variable, you can control the increment or decrement between iterations.
Q3. How can I read each line or word in a string using a for loop?
To read each line as a word in a string, you can replace line breaks with spaces using the printf command and command substitution. To read each word in a string, you can set the internal field separator (IFS) to a space.
Q4. Can I perform additional actions with each value in a for loop?
Yes, you can perform additional actions within the loop body for each value. This allows you to process the value, perform calculations, conditionally execute code, or update variables as needed.
Q5. Can I nest for loops in Bash scripting?
Yes, you can nest for loops in Bash scripting. This allows you to create more complex iterations and perform tasks on multiple levels of nested lists.
Q6. Are there any alternative loop constructs in Bash?
Yes, besides the for loop, Bash also provides while and until loops. While loops continue executing as long as a specified condition is true, while until loops continue executing until a specified condition becomes true.
Q7. How can I exit or skip a for loop prematurely?
You can use the break statement to exit a for loop prematurely. If you want to skip the current iteration and proceed to the next one, you can use the continue statement.