Bash For-Loops

The usefulness of the command-line, and especially scripts, increases exponentially once you master loops. And even though they might look scary, they are really not that hard.

The basic syntax of a loop is:

for VARIABLE in A LIST
do
  command1
  command2
  commandN
done

A LIST can be anything: file names, numbers, or strings. In most scripts, it will be a list of file names though. Now that we know how to create a loop, let’s look at our first script:

#!/bin/bash

echo "You can list numbers and text like this:"

for n in 1 2 3 four
do
  echo "Number $n"
done

echo "Or specify a range of numbers:"

for n in {1..5}
do
  echo "Number $n"
done

echo "Or use the output of another command:"
for f in $(ls)
do
  echo $f
done

In the last for-loop, I used the expression $(ls). This executes the command between parentheses and substitutes the result. In this case, ls gets executed and the for-loop is fed with the file names that ls prints out.

To start this script, we can do two things. First, we can run it with:

$ bash loop.sh

The second way, that I recommend, is making the file executable. The OS will know how to execute our file because of our shebang line at the top! Making the file executable is done by setting the file’s “execute flag” like this:

$ chmod +x loop.sh

You can now run the script with:

./loop.sh

The output in my case is:

$ ./loop.sh
You can just list a bunch of numbers and text like this:
1
2
3
four
Or specify a range of numbers:
1
2
3
4
5
Or use the output of another command:
loop.sh
notes.txt

It might differ for you, depending on which files are in the directory that you’re running the script in.


If you liked this page, please share it with a fellow learner: