The usefulness of the command-line, and especially scripts, increases exponentially once you master Bash for-loops. And even though they might look scary, they are really not that hard.
Syntax of a Bash for-loop
The basic syntax of a loop is:
for VARIABLE in A LIST
do
command1
command2
commandN
done
Example script
The A LIST
part can be anything: file names, numbers, or strings. In most scripts, it will be a list of file names though, since that’s what we’re often working with in Bash. 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.
Starting a Bash script
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.