Database examples

9 examples of for loops in Linux Bash scripts

fatmawati achmad zaenuri/Shutterstock.com

The versatile Bash for loop does more than just loop a certain number of times. We describe its many variations so that you can successfully use them in your own Linux scripts.

The for loop

All scripting and programming languages ​​have a way of handling loops. A loop is a section of code that you want to run repeatedly. Rather than typing the same set of statements into your script over and over, a loop will repeat a section of code over and over for you.

Celebration for the loop is very flexible. It can work with numbers, words, arrays, command line variables or the output of other commands. These are used in the on your mind of the loop. The header dictates what the loop works with – numbers or strings, for example – and what end condition will stop the loop.

The body of the loop contains the code you want to repeat. It contains what you want the loop to be do. The loop body can contain any valid script command.

A variable called loop counter or iterator is used to iterate over a range of values ​​or a list of data items. For each loop, the iterator takes the value of the next number, string, or data type that the loop iterates over. This allows the loop to work with the values ​​of each of the data items in turn, or even, in some cases, manipulate the data items themselves.

Simple for curls

If you’re looking to write your first for loop, these simple examples will get you started.

for loops using numeric lists

You can run a for loop on the command line. This command creates and runs a simple for loop. The iterator is a variable called i. We will assign i be each of the values ​​in the list of numbers, in turn. The loop body will print this value to the terminal window. The condition that terminates this loop is when i went through the whole list of numbers.

for i in 1 2 3 4 5; do echo $i; done

a for loop counting from 1 to 5

It is important to note here that the variable i is increased by one each time the loop runs, but that’s because the list of numbers increases by one each time.

This list of numbers starts at 3 and goes up in increments of two, then arbitrarily jumps to 44.

for i in 3 5 7 9 11 44; do echo $i; done

a for loop counting in a non-sequential list of numbers

It makes no difference to the for loop. It starts at one end of the list and uses each value in turn, until all the values ​​in the list have been used.

The numbers also don’t need to be in ascending order. They can be in any order.

for i in 3 43 44 11 9; do echo $i; done

a for loop counting in an unsorted list of numbers

for loops using wordlists

We can just as well do the same with words. Copy the text of the script into an editor and save it as “word-list.sh”.

#!/bin/bash

for word in This is a sequence of words
do 
  echo $word
done

You will need to use chmod to make the script executable, and any other scripts you copy from this article. Simply replace the script name each time you use the chmod ordered.

chmod +x word-list.sh

Make a script executable with chmod

Let’s run the script.

./word-list.sh

A for loop working on a list of words

Just as it did with numbers, the iterator – in this example, the variable word— iterates through the list of data items until it reaches the end of the list. The loop body accesses the value in the word variable and so every word in the list is processed.

for loops with number ranges

If you wanted a for loop to run 100 times, it would be quite cumbersome to have to enter a sequence of 100 digits in the loop header. Number ranges allow you to specify only the first and last number.

This script is “number-range.sh”.

#!/bin/bash

for i in {1..10}
do
  echo "Loop spin:" $i
done

The range of numbers is defined in braces”{}“with two periods”..” separating the numbers that start and end the range. Make sure you don’t include a space in the range definition.

Here’s how it works:

./number-range.sh

A for loop using a range of numbers

You can include another number that defines the step size the iterator should use to iterate through the numbers in the range. This script, “number-range2.sh” will use a range of 0 to 32 and a step size of 4.

#!/bin/bash

for i in {0..32..4}
do
  echo "Loop spin:" $i
done

The iterator traverses the range of numbers in hops of four.

./number-range2.sh

A for loop using an iterative step of 4

for loops using filenames

Because we can deal with lists of words, we can make our scripts work with filenames. This script is called “filenames.sh”.

#!/bin/bash

for file in word-list.sh number-range.sh number-range2.sh filenames.sh
do
  ls -lh "$file"
done

It would be pretty useless to have a script that only does what ls can do, but it shows how to access filenames inside the loop body.

./filenames.sh

A for loop using a list of filenames

Similar to using the number range, we can use a file pattern in the loop header to specify the files we want to process. This saves a lot of typing and means we don’t need to know the file names in advance.

This script is called “filenames2.sh”. We replaced the list of filenames with the “*.sh” filename pattern so that the script report is for all script files in the current directory.

#!/bin/bash

for file in *.sh
do
  ls -lh "$file"
done

Here is the output.

./filenames2.sh

A for loop using a *.sh file template

for loops using command line parameters

We can add a bit more flexibility by passing the filename pattern on the command line. The $* The variable represents any command line parameters passed to the script.

It is “filenames3.sh”.

#!/bin/bash

for file in $*
do
  ls -lh "$file"
done

We will ask for filenames starting with “n” and having an SH extension.

./filenames3.sh n*.sh

A for loop taking a file template as a command line parameter

We may also transmit more than one pattern at a time.

./filenames3.sh n*.sh .bashrc

A for loop taking a file template and the command line parameters of a filename

The iterator variable file takes the value of each of the command line parameters. Filename patterns are expanded and all filenames are processed in the loop body.

RELATED: How to work with variables in Bash

C-like for loops

Bash supports the classic three-term for loop, like those found in the C programming language. They are called three-term for loops because there are three terms in the loop header.

  • The initial value of the loop iterator.
  • The test to know if the loop continues or ends.
  • The increment or decrement of the iterator.

This script is “c-like.sh”.

The iterator I is set to 1 at the start of the loop, and the loop will run as long as the statement ” i<=10 ” is true. As soon as i reached 11 years old, for the loop will stop. The iterator is increased by one for each revolution of the loop.

#!/bin/bash

for (( i=1; i<=10; i++ ))
do 
  echo "Loop number:" $i
done

Let’s run this script.

./c-like.sh

A three-term or C-like for loop

The C-like for loop makes it easy to create for loops that have slightly odd requirements. This loop starts at 15 and counts down in steps of 3. This is “c-like2.sh”

#!/bin/bash

for (( i=15; i>0; i-=3 ))
do 
  echo "Loop number:" $i
done

When we run it, it should go back in steps of three.

./c-like2.sh

A C-like for loop counting down

Infinity for curls

You can also use this format of for loop to create an infinite loop. All you have to do is remove all the elements from the loop header, like this. It’s “infinity.sh.”

#!/bin/bash

for (( ; ; ))
do
  echo "Press Ctrl+C to stop..."
  sleep 1
done

You will need to press Ctrl + C to stop the loop.

./infinite.sh

A C-like infinite for loop

for loops using arrays of words

We can easily iterate over an array of words. We need to provide the array name in the loop header, and the iterator will loop through all the array entries. It is “word-array.sh”.

#!/bin/bash

distributions=("Ubuntu Fedora Manjaro Arch EndeavourOS Garuda")

for distro in $distributions
do
  echo $distro
done

All distributions are listed for us.

./word-array.sh

A for loop using an array of words

The continue command

If you want the loop to loop over a particular input, test if the iterator matches that input and use the continue ordered. The continue the command abandons the running rotation of the loop. It increments the iterator and starts the next rotation of the loop, assuming the input you want to skip isn’t the last item in the list.

It is “word-array2.sh”. It spans the “Arch” array entry but processes all other array members.

#!/bin/bash

distributions=("Ubuntu Fedora Manjaro Arch EndeavourOS Garuda")

for distro in $distributions
do
  if [[ "$distro" == "Arch" ]] ;
    then
    continue
  fi
  echo $distro
done

“Arch” does not appear in the terminal window.

./word-array2.sh

A for loop skipping an entry in a word array because of the continue command

The break command

The break The command breaks out of the loop and prevents further processing.

It is “word-array3.sh”. This is the same as the previous script with continue replaced by break.

#!/bin/bash

distributions=("Ubuntu Fedora Manjaro Arch EndeavourOS Garuda")

for distro in $distributions
do
  if [[ "$distro" == "Arch" ]] ;
    then
    break
  fi
  echo $distro
done

When the iterator contains “Arch”, the for loop drops any further processing.

./word-array3.sh

A for loop aborting further processing because of the break command

for loops using associative arrays

In Bash 4 and above, associative arrays let you create lists of key-value pairs that can be searched by key or by value. Due to the two-way relationship between key and value, they are also called data dictionaries.

We can iterate through an associative array using a for loop. This script is “associative.sh”. It defines an associative array with four entries, one for each of “dog”, “cat”, “robin” and “human”. These are the keys. The values ​​are the (default) number of legs they each have.

#!/bin/bash

declare -A animals=( [dog]=Four-legged [cat]=Four-legged [robin]=Two-legged [human]=Two-legged )

for legs in ${!animals[@]}
do
  if [ ${animals[$legs]} == "Two-legged" ]; then 
    echo ${legs}
  fi
done

The iterator is called legs . Note that the loop header contains a “!” exclamation mark. This does not act like the logical NOT operator, it is part of the associative array syntax. It is necessary to search through the array.

The loop body performs a string comparison test. If the value of the array member is “Two-legged”, it prints the key value to the terminal window. When we run it, the script prints the two-legged creatures.

./associative.sh

Using a for loop to extract elements from an associative array

Iterating over command output

If you have a command or sequence of commands that produces a list of something, like filenames, you can loop through them with a for loop. You have to watch out for unexpected filename extensions, but in simple cases it’s fine.

This script is “command.sh”. he uses ls and wc to provide a sorted list of script filenames, along with their line, word, and byte counts.

#!/bin/bash

for i in $(ls *.sh | sort);
do 
  echo $(wc $i)
done

When we run it, we get the statistics for each file, with the files listed in alphabetical order.

./command.sh

Using a for loop to iterate over the output of two piped commands

The dazzling for the loop

The for loop is a versatile and easy to understand scripting tool. But as flexible as it is, remember that other loops exist for a reason. Don’t be dazzled by thinking that for loop is all you will need.

The while loop, for example, is much better suited to some things than the for loop, like reading lines from a file.

Writing good scripts means using the most suitable tool for the task at hand. The for loop is a great tool to have in your trick toolbox.