How to Loop Over Tuples in Bash (With Example)


Often you may want to loop over tuples in Bash.

You can use the following syntax to do so:

for i in "A 1" "B 2" "C 3" "D 4"
do
    set -- $i
    echo $1 $2
done

This particular example will print out each element in each tuple, separated by a space.

Note that we use the set command to convert each element in each tuple into arguments $1, $2, etc.

We are then able to use the echo command to output the element of each tuple, using $1 and $2 as references to each element.

The following example shows how to use this syntax in practice.

Example: How to Loop Over Tuples in Bash

Suppose that we would like to loop over the following tuples in Bash in which the first element of each tuple is a letter and the second element is a number:

  • A 1
  • B 2
  • C 3
  • D 4

We can use the following syntax to do so:

for i in "A 1" "B 2" "C 3" "D 4"
do
    set -- $i
    echo $1 $2
done

The following screenshot shows how to use this syntax in practice:

Bash loop over tuples

The output displays each element from each tuple, separated with a space.

Note that we could also use a different separator between the elements of each tuple if we would like.

For example, we could use the following syntax to separate the elements with a colon instead:

for i in "A 1" "B 2" "C 3" "D 4"
do
    set -- $i
    echo $1:$2
done

The following screenshot shows how to use this syntax in practice:

The output displays each element from each tuple, separated with a colon.

Feel free to use similar syntax to loop over the elements in your own tuples.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to List All Files in Folder by Size
Bash: How to List All Files in Folder Without Extension
Bash: How to List All Files Matching a Specific Pattern

Leave a Reply