Bash Examples: for loop

March 1, 2023

This guide is part of the "Snippets" series. This series is focused on providing simple and accessible tutorials on various topics relating to development!

Bash "for loop" is a control structure in the Bash scripting language that allows you to execute a block of code repeatedly based on a set of values or elements. The syntax for a "for loop" in Bash is as follows:

for variable_name in list
    # code block to be executed

The list can be a sequence of values separated by spaces, a range of values, or a list of filenames, and the variable_name is the variable that will be used to store each value or element in the list during each iteration of the loop.

Here are some examples of Bash "for loop" using different types of lists:

  1. Iterating over a sequence of numbers:
for i in {1..5}
    echo $i
  1. Iterating over a list of filenames:
for file in *.txt
    echo $file

This will output the names of all the text files in the current directory.

  1. Iterating over a range of numbers:
for i in $(seq 1 2 10)
    echo $i

In this example, the seq command generates a sequence of numbers from 1 to 10 with a step of 2, which is then used as the list for the "for loop".

  1. Iterating over an array:
my_array=("apple" "banana" "cherry" "date")

for fruit in "${my_array[@]}"
    echo $fruit

This will output:


In this example, the array my_array contains four elements, and the "${my_array[@]}" syntax is used to expand the array into a list of values that can be used by the "for loop".

Note that you can use any variable name for variable_name, but it's a convention to use a single letter variable like i or j for iterating over numbers, and more descriptive names for iterating over other types of lists.

Also, make sure to use the correct syntax for the type of list you are iterating over, and always test your loops with a small set of values before using them with larger sets.

Here are some other concrete/niche examples of using the Bash "for loop" in different scenarios:

  1. Iterating over the lines of a file:
for line in $(cat myfile.txt)
    echo $line

This will output each line of the file myfile.txt as a separate value in the list.

  1. Performing an operation on a set of files:
for file in *.jpg
    convert $file -resize 50% small-$file

This will use the convert command to resize each JPEG file in the current directory to 50% of its original size, and save the new file with a "small-" prefix.

  1. Running a command on a set of remote hosts:
for host in host1 host2 host3
    ssh $host "sudo apt-get update && sudo apt-get upgrade -y"

This will SSH into each of the remote hosts host1, host2, and host3, and run the commands sudo apt-get update and sudo apt-get upgrade -y to update the system packages.

  1. Iterating over a list of URLs and downloading the files:
urls=("" "" "")

for url in "${urls[@]}"
    wget $url

You might also like

The latest from the blog