Bash Script for Loop Explained with Examples

Introduction

The for loop is an essential programming functionality that goes through a list of elements. For each of those elements, the for loop performs a set of commands. The command helps repeat processes until a terminating condition.

Whether you’re going through an array of numbers or renaming files, for loops in Bash scripts provide a convenient way to list items automatically.

This tutorial shows how to use Bash for loops in scripts.

Bash for Loop Explained with Examples

Prerequisites

  • Access to the terminal/command line (CTRL+ALT+T).
  • A text editor, such as Nano or Vi/Vim.
  • Elementary programming terminology.

Bash Script for Loop

Use the for loop to iterate through a list of items to perform the instructed commands.

The basic syntax for the for loop in Bash scripts is:

for <element> in <list>
do
<commands>
done

The element, list, and commands parsed through the loop vary depending on the use case.

Bash For Loop Examples

Below are various examples of the for loop in Bash scripts. Create a script, add the code, and run the Bash scripts from the terminal to see the results.

Individual Items

Iterate through a series of given elements and print each with the following syntax:

#!/bin/bash
# For loop with individual numbers
for i in 0 1 2 3 4 5
do
echo "Element $i"
done

individual.sh for loop script

Run the script to see the output:

. <script name>

individual.sh terminal output

The script prints each element from the provided list to the console.

Alternatively, use strings in a space separated list:

#!/bin/bash
# For loop with individual strings
for i in "zero" "one" "two" "three" "four" "five"
do
echo "Element $i"
done

individual_strings.sh for loop script

Save the script and run from the terminal to see the result.

individual_strings.sh terminal output

The output prints each element to the console and exits the loop.

Range

Instead of writing a list of individual elements, use the range syntax and indicate the first and last element:

#!/bin/bash
# For loop with number range
for i in {0..5}
do
echo "Element $i"
done

range.sh for loop script

The script outputs all elements from the provided range.

range.sh terminal output

The range syntax also works for letters. For example:

#!/bin/bash
# For loop with letter range
for i in {a..f}
do
echo "Element $i"
done

range_letters.sh for loop script

The script outputs letters to the console in ascending order in the provided range.

range_letters.sh terminal output

The range syntax works for elements in descending order if the starting element is greater than the ending.

For example:

#!/bin/bash
# For loop with reverse number range
for i in {5..0}
do
echo "Element $i"
done

range_reverse.sh for loop script

The output lists the numbers in reverse order.

range_reverse.sh terminal output

The range syntax works whether elements increase or decrease.

Range with Increment

Use the range syntax and add the step value to go through the range in intervals.

For example, use the following code to list even numbers:

#!/bin/bash
# For loop with range increment numbers
for i in {0..10..2}
do
echo "Element $i"
done

increment.sh for loop script

The output prints every other digit from the given range.

increment.sh terminal output

Alternatively, loop from ten to zero counting down by even numbers:

#!/bin/bash
# For loop with reverse range increment numbers
for i in {10..0..2}
do
echo "Element $i"
done

increment_reverse.sh for loop script

Execute the script to print every other element from the range in decreasing order.

increment_reverse.sh terminal output

Exchange increment 2 for any number less than the distance between the range to get values for different intervals.

The seq Command

The seq command generates a number sequence. Parse the sequence in the Bash script for loop as a command to generate a list.

For example:

#!/bin/bash
# For loop with seq command
for i in $(seq 0 2 10)
do
echo "Element $i"
done

seq.sh for loop script

The output prints each element generated by the seq command.

The seq command is a historical command and not a recommended way to generate a sequence. The curly braces built-in methods are preferable and faster.

C-Style

Bash scripts allow C-style three parameter for loop control expressions. Add the expression between double parentheses as follows:

#!/bin/bash
# For loop C-style
for (( i=0; i<=5; i++ ))
do
echo "Element $i"
done

cstyle.sh for loop script

The expression consists of:

  • The initializer (i=0) determines the number where the loop starts counting.
  • Stop condition (i<=5) indicates when the loop exits.
  • Step (i++) increments the value of i until the stop condition.

Separate each condition with a semicolon (;). Adjust the three values as needed for your use case.

The terminal outputs each element, starting with the initializer value.

cstyle.sh terminal output

The value increases by the step amount, up to the stop condition.

Infinite Loops

Infinite for loops do not have a condition set to terminate the loop. The program runs endlessly because the end condition does not exist or never fulfills.

To generate an infinite for loop, add the following code to a Bash script:

#!/bin/bash
# Infinite for loop
for (( ; ; ))
do
echo "CTRL+C to exit"
done

infinite.sh for loop script

To terminate the script execution, press CTRL+C.

infinite.sh terminal output

Infinite loops are helpful when a program runs until a particular condition fulfills.

Break

The break statement ends the current loop and helps exit the for loop early. This behavior allows exiting the loop before meeting a stated condition.

To demonstrate, add the following code to a Bash script:

#!/bin/bash
# Infinite for loop with break
i=0
for (( ; ; ))
do
echo "Iteration: ${i}"
(( i++ ))
if [[ i -gt 10 ]]
then
break;
fi
done
echo "Done!"

break.sh for loop script

The example shows how to exit an infinite for loop using a break. The Bash if statement helps check the value for each integer and provides the break condition. This terminates the script when an integer reaches the value ten.

break.sh terminal output

To exit a nested loop and an outer loop, use break 2.

Continue

The continue command ends the current loop iteration. The program continues the loop, starting with the following iteration. To illustrate, add the following code to a Bash script to see how the continue statement works in a for loop:

#!/bin/bash
# For loop with continue statement
for i in {1..100}
do
if [[ $i%11 -ne 0 ]]
then
continue
fi
echo $i
done

continue.sh for loop script

The code checks numbers between one and one hundred and prints only numbers divisible by eleven.

continue.sh terminal output

The conditional if statement checks for divisibility, while the continue statement skips any numbers which have a remainder when divided by eleven.

Arrays

Arrays store a list of elements. The for loop provides a method to go through arrays by element.

For example, define an array and loop through the elements with:

#!/bin/bash
# For loop with array
array=(1 2 3 4 5)
for i in ${array[@]}
do
echo "Element $i"
done

array.sh for loop script

The output prints each element stored in the array from first to last.

array.sh terminal output

The Bash for loop is the only method to iterate through individual array elements.

Indices

When working with arrays, each element has an index.

List through an array’s indices with the following code:

#!/bin/bash
# For loop with array indices
array=(1 2 3 4 5)
for i in ${!array[@]}
do
echo "Array indices $i"
done

indices.sh for loop script

Element indexing starts at zero. Therefore, the first element has an index zero.

indices.sh terminal output

The output prints numbers from zero to four for an array with five elements.

Nested Loops

To loop through or generate multi-dimensional arrays, use nested for loops.

As an example, generate decimal values from zero to three using nested loops:

#!/bin/bash
# Nested for loop
for (( i = 0; i <= 2; i++ ))
do
for (( j = 0 ; j <= 9; j++ ))
do
echo -n " $i.$j "
done
echo "" 
done

nested.sh for loop script

The code does the following:

  • Line 1 starts the for loop at zero, increments by one, and ends at two, inclusive.
  • Line 3 starts the nested for loop at zero. The value increments by one and ends at nine inclusively.
  • Line 5 prints the values from the for loops. The nested for loops through all numbers three times, once for each outer loop value.

nested.sh terminal output

The output prints each number combination to the console and enters a new line when the outer loop finishes one iteration.

Strings

To loop through words in a string, store the string in a variable. Then, parse the variable to a for loop as a list.

For example:

#!/bin/bash
# For loop with string
strings="I am a string"
for i in ${strings}
do
echo "String $i"
done

string.sh for loop script

The loop iterates through the string, with each word being a separate element.

string.sh terminal output

The output prints individual words from the string to the console.

Files

The for loop combined with proximity searches helps list or alter files that meet a specific condition.

For example, list all Bash scripts in the current directory with a for loop:

#!/bin/bash
# For loop with files
for f in *.sh
do
echo $f
done

files.sh for loop script

The script searches through the current directory and lists all files with the .sh extension.

files.sh terminal output

Loop through files or directories to automatically rename or change permissions for multiple elements at once.

Command Substitution

The for loop accepts command substitution as a list of elements to iterate through.

The next example demonstrates how to write a for loop with command substitution:

#!/bin/bash
# For loop with command substitution
list=`cat list.txt`
# Alternatively, use list=$(cat list.txt)
for i in $list
do
echo $i
done

command.sh for loop script

The Bash comment offers an alternative syntax for command substitution. The code reads the contents of the list.txt file using the cat command and saves the information to a variable list.

command.sh and list.txt terminal output

Use the command substitution method to rename files from a list of names saved in a text file.

Command Line Arguments

Use the for loop to iterate through command line arguments.

The following example code demonstrates how to read command line arguments in a for loop:

#!/bin/bash
# For loop expecting command line arguments
for i in [email protected]
do
echo "$i"
done

arguments.sh for loop script

Provide the command line arguments when you run the Bash script.

For example:

. <script name> foo bar

arguments.sh terminal output

The [email protected] substitutes each command line argument into the for loop.

Conclusion

After following this tutorial, you know how to use the for loop in Bash scripts to iterate through lists.

Next, learn how to write and use Bash functions.

原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/222371.html

(0)
上一篇 2022年1月6日
下一篇 2022年1月6日

相关推荐

发表回复

登录后才能评论