Loops
Overview
Teaching: 35 min
Exercises: 15 minQuestions
How can I perform the same actions on many different files?
Objectives
Write a loop that applies one or more commands separately to each file in a set of files.
Trace the values taken on by a loop variable during execution of the loop.
Explain the difference between a variable’s name and its value.
Explain why spaces and some punctuation characters shouldn’t be used in file names.
Demonstrate how to see what commands have recently been executed.
Re-run recently executed commands without retyping them.
Loops are a programming construct which allow us to repeat a command or set of commands for each item in a list. As such they are key to productivity improvements through automation. Similar to wildcards and tab completion, using loops also reduces the amount of typing required (and hence reduces the number of typing mistakes).
Suppose we have several hundred files containing population time series data.
For this example, we’ll use the exercise-data/populations
directory which only has six such files,
but the principles can be applied to many many more files at once. Each file contains population time series for one species, from the Living Planet Database of the Living Planet Index.
The structure of these files is the same: each line gives data for one population time series, as tab-delimited text.
Column headings are given on the first line of the combined-data file six_species.csv
, which can be displayed as follows:
$ head -n 1 six-species.csv
Let’s look at the files:
$ head -n 5 bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt
Due to the amount of data in each line, the output is visually confusing.
We would like to print out the class (high-level classification) for the species in each file. Class is given in the fifth column.
For each file, we would need to execute the command cut -f 5
and pipe this to sort
and uniq
.
We’ll use a loop to solve this problem, but first let’s look at the general form of a loop,
using the pseudo-code below:
for thing in list_of_things
do
operation_using $thing # Indentation within the loop is not required, but aids legibility
done
and we can apply this to our example like this:
$ for filename in bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt
> do
> cut -f 5 $filename | sort | uniq
> done
Aves
Aves
Reptilia
Elasmobranchii
Amphibia
Mammalia
This shows us the first two files contain data on a species in the class Aves, the third contains data on a species in Reptilia, and so on.
Follow the Prompt
The shell prompt changes from
$
to>
and back again as we were typing in our loop. The second prompt,>
, is different to remind us that we haven’t finished typing a complete command yet. A semicolon,;
, can be used to separate two commands written on a single line.
When the shell sees the keyword for
,
it knows to repeat a command (or group of commands) once for each item in a list.
Each time the loop runs (called an iteration), an item in the list is assigned in sequence to
the variable, and the commands inside the loop are executed, before moving on to
the next item in the list.
Inside the loop,
we call for the variable’s value by putting $
in front of it.
The $
tells the shell interpreter to treat
the variable as a variable name and substitute its value in its place,
rather than treat it as text or an external command.
In this example, the list is six filenames: bowerbird.txt
, dunnock.txt
, python.txt
, shark.txt
, toad.txt
and wildcat.txt
.
Each time the loop iterates, it will assign a file name to the variable filename
and run the cut
command.
The first time through the loop,
$filename
is bowerbird.txt
.
The interpreter runs the command cut -f 5
on bowerbird.txt
and pipes the output to the sort
command. Then it pipes the output of the sort
command to the uniq
command, which
prints its output to the terminal.
For the second iteration, $filename
becomes
dunnock.txt
.
The interpreter runs the command cut -f 5
on dunnock.txt
and pipes the output to the sort
command. Then it pipes the output of the sort
command to the uniq
command, which
prints its output to the terminal.
This continues until each of the filenames in turn has been assigned to the variable $filename
.
After the final item, wildcat.txt
, the shell exits the for
loop.
Same Symbols, Different Meanings
Here we see
>
being used as a shell prompt, whereas>
is also used to redirect output. Similarly,$
is used as a shell prompt, but, as we saw earlier, it is also used to ask the shell to get the value of a variable.If the shell prints
>
or$
then it expects you to type something, and the symbol is a prompt.If you type
>
or$
yourself, it is an instruction from you that the shell should redirect output or get the value of a variable.
When using variables it is also
possible to put the names into curly braces to clearly delimit the variable
name: $filename
is equivalent to ${filename}
, but is different from
${file}name
. You may find this notation in other people’s programs.
We have called the variable in this loop filename
in order to make its purpose clearer to human readers.
The shell itself doesn’t care what the variable is called;
if we wrote this loop as:
$ for x in bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt
> do
> cut -f 5 $x | sort | uniq
> done
or:
$ for temperature in bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt
> do
> cut -f 5 $temperature | sort | uniq
> done
it would work exactly the same way.
Don’t do this.
Programs are only useful if people can understand them,
so meaningless names (like x
) or misleading names (like temperature
)
increase the odds that the program won’t do what its readers think it does.
In the above examples, the variables (thing
, filename
, x
and temperature
)
could have been given any other name, as long as it is meaningful to both the person
writing the code and the person reading it.
Note also that loops can be used for other things than filenames, like a list of numbers or a subset of data.
Write your own loop
How would you write a loop that echoes all 10 numbers from 0 to 9?
Solution
$ for loop_variable in 0 1 2 3 4 5 6 7 8 9 > do > echo $loop_variable > done
0 1 2 3 4 5 6 7 8 9
Variables in Loops
This exercise refers to the
shell-lesson-data/exercise-data/populations
directory.ls *.txt
gives the following output:bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt
What is the output of the following code?
$ for datafile in *.txt > do > ls *.txt > done
Now, what is the output of the following code?
$ for datafile in *.txt > do > ls $datafile > done
Why do these two loops give different outputs?
Solution
The first code block gives the same output on each iteration through the loop. Bash expands the wildcard
*.txt
within the loop body (as well as before the loop starts) to match all files ending in.txt
and then lists them usingls
. The expanded loop would look like this:$ for datafile in bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt > do > ls bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt > done
bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt
The second code block lists a different file on each loop iteration. The value of the
datafile
variable is evaluated using$datafile
, and then listed usingls
.bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt
Limiting Sets of Files
What would be the output of running the following loop in the
shell-lesson-data/exercise-data/populations
directory?$ for filename in t* > do > ls $filename > done
- No files are listed.
- All files are listed.
- Only
python.txt
toad.txt
andwildcat.txt
are listed.- Only
toad.txt
is listed.Solution
4 is the correct answer.
*
matches zero or more characters, so any file name starting with the lettert
, followed by zero or more other characters will be matched.How would the output differ from using this command instead?
$ for filename in *t* > do > ls $filename > done
- The same files will be listed.
- The files
bowerbird.txt
,dunnock.txt
,python.txt
,shark.txt
,toad.txt
andwildcat.txt
will be listed.- No files are listed this time.
- The files
python.txt
andtoad.txt
will be listed.- Only the file
six-species.csv
will be listed.Solution
2 is the correct answer.
*
matches zero or more characters, so a file name with zero or more characters before a lettert
and zero or more characters after the lettert
will be matched. In other words, and file name containing at least onet
will be listed.
Saving to a File in a Loop - Part One
In the
shell-lesson-data/exercise-data/populations
directory, what is the effect of this loop?for species in *.txt do echo $species cat $species > species.txt done
- Prints
bowerbird.txt
,dunnock.txt
,python.txt
,shark.txt
,toad.txt
andwildcat.txt
, and the text fromwildcat.txt
will be saved to a file calledspecies.txt
.- Prints
bowerbird.txt
,dunnock.txt
,python.txt
,shark.txt
, ,toad.txt
andwildcat.txt
, and the text from all six files would be concatenated and saved to a file calledspecies.txt
.- Prints
bowerbird.txt
,dunnock.txt
,python.txt
,shark.txt
,toad.txt
andwildcat.txt
, and the text frombowerbird.txt
will be saved to a file calledspecies.txt
.- None of the above.
Solution
- The text from each file in turn gets written to the
species.txt
file. However, the file gets overwritten on each loop iteration, so the final content ofspecies.txt
is the text from thewildcat.txt
file.
Saving to a File in a Loop - Part Two
Also in the
shell-lesson-data/exercise-data/populations
directory, remove the file you created above:rm species.txt
Use
ls
to check you only have the files we provided, i.e.bowerbird.txt dunnock.txt python.txt shark.txt six-species.csv toad.txt wildcat.txt
Now, what would be the output of the following loop?
for datafile in *.txt do cat $datafile >> all.txt done
- All of the text from
bowerbird.txt
,dunnock.txt
,python.txt
,shark.txt
andtoad.txt
would be concatenated and saved to a file calledall.txt
.- The text from
bowerbird.txt
will be saved to a file calledall.txt
.- All of the text from
bowerbird.txt
,dunnock.txt
,python.txt
,shark.txt
,toad.txt
andwildcat.txt
would be concatenated and saved to a file calledall.txt
.- All of the text from
bowerbird.txt
,dunnock.txt
,python.txt
,shark.txt
,toad.txt
andwildcat.txt
would be printed to the screen and saved to a file calledall.txt
.Solution
3 is the correct answer.
>>
appends to a file, rather than overwriting it with the redirected output from a command. Given the output from thecat
command has been redirected, nothing is printed to the screen.
Here’s a slightly more complicated loop:
$ for filename in *.txt
> do
> echo $filename
> head -n 10 $filename | tail -n 1
> done
The shell starts by expanding *.txt
to create the list of files it will process.
The loop body
then executes two commands for each of those files.
The first command, echo
, prints its command-line arguments to standard output.
For example:
$ echo hello there
prints:
hello there
In this case,
since the shell expands $filename
to be the name of a file,
echo $filename
prints the name of the file.
Note that we can’t write this as:
$ for filename in *.txt
> do
> $filename
> head -n 10 $filename | tail -n 1
> done
because then the first time through the loop,
when $filename
expanded to bowerbird.txt
, the shell would try to run bowerbird.txt
as
a program.
Finally,
the head
and tail
combination selects line 10
from whatever file is being processed
(assuming the file has at least 10 lines; otherwise it selects the last line of the file).
Spaces in Names
Spaces are used to separate the elements of the list that we are going to loop over. If one of those elements contains a space character, we need to surround it with quotes, and do the same thing to our loop variable. Suppose our data files are named:
red dragon.txt purple unicorn.txt
To loop over these files, we would need to add double quotes like so:
$ for filename in "red dragon.txt" "purple unicorn.txt" > do > head -n 10 "$filename" | tail -n 1 > done
It is simpler to avoid using spaces (or other special characters) in filenames.
The files above don’t exist, so if we run the above code, the
head
command will be unable to find them, however the error message returned will show the name of the files it is expecting:head: cannot open 'red dragon.txt' for reading: No such file or directory head: cannot open 'purple unicorn.txt' for reading: No such file or directory
Try removing the quotes around
$filename
in the loop above to see the effect of the quote marks on spaces.head: cannot open 'red' for reading: No such file or directory head: cannot open 'dragon.txt' for reading: No such file or directory head: cannot open 'purple' for reading: No such file or directory head: cannot open 'unicorn.txt' for reading: No such file or directory
We would like to modify each of the six files for individual species in
shell-lesson-data/exercise-data/populations
,
but also save a version
of the original files, naming the copies original-bowerbird.txt
, original-dunnock.txt
,
original-python.txt
, and so on.
We can’t use:
$ cp *.txt original-*.txt
because that would expand to:
$ cp bowerbird.txt dunnock.txt python.txt shark.txt toad.txt wildcat.txt original-*.txt
This wouldn’t back up our files, instead we get an error:
cp: target `original-*.txt' is not a directory
This problem arises when cp
receives more than two inputs. When this happens, it
expects the last input to be a directory where it can copy all the files it was passed.
Since there is no directory named original-*.txt
in the populations
directory we get an
error.
Instead, we can use a loop:
$ for filename in *.txt
> do
> cp $filename original-$filename
> done
This loop runs the cp
command once for each filename.
The first time,
when $filename
expands to bowerbird.txt
,
the shell executes:
cp bowerbird.txt original-bowerbird.txt
The second time, the command is:
cp dunnock.txt original-dunnock.txt
The third time, the command is:
cp python.txt original-python.txt
and so on, until a copy of each of the six files has been made.
Since the cp
command does not normally produce any output, it’s hard to check
that the loop is doing the correct thing.
However, we learned earlier how to print strings using echo
, and we can modify the loop
to use echo
to print our commands without actually executing them.
As such we can check what commands would be run in the unmodified loop.
The following diagram
shows what happens when the modified loop is executed, and demonstrates how the
judicious use of echo
is a good debugging technique.
Keyboard shortcuts for moving around the command line
We can move to the beginning of a line in the shell by typing Ctrl+A and to the end using Ctrl+E. This may be easier and faster than using the left and right cursor keys.
An extensive range of shortcuts is provided by the shell. To discover more, try a Web search for “bash keyboard shortcuts”.
Those Who Know History Can Choose to Repeat It
Another way to repeat previous work is to use the
history
command to get a list of the last few hundred commands that have been executed, and then to use!123
(where ‘123’ is replaced by the command number) to repeat one of those commands. For example, if a user types this:$ history | tail -n 5
and happens to see this in the output:
456 ls -l NENE0*.txt 457 rm stats-NENE01729B.txt.txt 458 bash goostats.sh NENE01729B.txt stats-NENE01729B.txt 459 ls -l NENE0*.txt 460 history
then she can re-run
goostats.sh
onNENE01729B.txt
simply by typing!458
.
Other History Commands
There are a number of other shortcut commands for getting at the history.
- Ctrl+R enters a history search mode ‘reverse-i-search’ and finds the most recent command in your history that matches the text you enter next. Press Ctrl+R one or more additional times to search for earlier matches. You can then use the left and right arrow keys to choose that line and edit it then hit Return to run the command.
!!
retrieves the immediately preceding command (you may or may not find this more convenient than using ↑)!$
retrieves the last word of the last command. That’s useful more often than you might expect: afterbash goostats.sh NENE01729B.txt stats-NENE01729B.txt
, you can typeless !$
to look at the filestats-NENE01729B.txt
, which is quicker than doing ↑ and editing the command-line.
Doing a Dry Run
A loop is a way to do many things at once — or to make many mistakes at once if it does the wrong thing. One way to check what a loop would do is to
echo
the commands it would run instead of actually running them.Suppose we want to preview the commands the following loop will execute without actually running those commands:
$ for datafile in *.txt > do > cat $datafile >> all.txt > done
What is the difference between the two loops below, and which one would we want to run?
# Version 1 $ for datafile in *.txt > do > echo cat $datafile >> all.txt > done
# Version 2 $ for datafile in *.txt > do > echo "cat $datafile >> all.txt" > done
Solution
The second version is the one we want to run. This prints to screen everything enclosed in the quote marks, expanding the loop variable name because we have prefixed it with a dollar sign. It also does not modify nor create the file
all.txt
, as the>>
is treated literally as part of a string rather than as a redirection instruction.The first version appends the output from the command
echo cat $datafile
to the file,all.txt
. This file will just contain the list;cat bowerbird.txt
,cat dunnock.txt
,cat python.txt
etc.Try both versions for yourself to see the output! Be sure to open the
all.txt
file to view its contents.
Nested Loops
Suppose we want to set up a directory structure to organize some experiments measuring reaction rate constants with different compounds and different temperatures. What would be the result of the following code:
$ for species in bowerbird dunnock python > do > for continent in Africa Asia Europe > do > mkdir $species-$continent > done > done
Solution
We have a nested loop, i.e. contained within another loop, so for each species in the outer loop, the inner loop (the nested loop) iterates over the list of three continents, and creates a new directory for each combination.
Try running the code for yourself to see which directories are created!
Key Points
A
for
loop repeats commands once for every thing in a list.Every
for
loop needs a variable to refer to the thing it is currently operating on.Use
$name
to expand a variable (i.e., get its value).${name}
can also be used.Do not use spaces, quotes, or wildcard characters such as ‘*’ or ‘?’ in filenames, as it complicates variable expansion.
Give files consistent names that are easy to match with wildcard patterns to make it easy to select them for looping.
Use the up-arrow key to scroll up through previous commands to edit and repeat them.
Use Ctrl+R to search through the previously entered commands.
Use
history
to display recent commands, and![number]
to repeat a command by number.