Overview

Teaching: 15 min
Exercises: 0 min
Questions
  • 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 key to productivity improvements through automation as they allow us to execute commands repetitively. Similar to wildcards and tab completion, using loops also reduces the amount of typing (and typing mistakes).

Let’s do something on all the images.

We would like to modify these files, but also save a version of the original files, naming the copies original-1411.jpg and so on. We can’t use:

$ cp *.jpg original-*.jpg

because that would expand to:

$ cp 1141.dat 1142.dat original-*.jpg

This wouldn’t back up our files, instead we get an error:

cp: target `original-*.jpg' 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-*.jpg in the pictures directory we get an error.

Instead, we can use a loop to do some operation once for each thing in a list. Here’s a simple example that displays the first three lines of each file in turn:

$ for filename in 1411.jpg 1412.jpg
> do
>    echo $filename
> done

When the shell sees the keyword for, it knows to repeat a command (or group of commands) once for each thing in a list. For each iteration, the name of the each thing is sequentially assigned to the variable and the commands inside the loop are executed before moving on to the next thing 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 two filenames: 1411.jpg and 1412.jpg. Each time the loop iterates, it will assign a file name to the variable filename and run the head command. The first time through the loop, $filename is 1141.jpg. The interpreter runs the command echo on 1141.jpg, and the prints the string 1141.jpg. For the second iteration, $filename becomes 1142.jpg. This time, the shell runs echo on 1142.jpg and prints 1142.jpg. Since the list was only two items, the shell exits the for loop.

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.

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.

Same Symbols, Different Meanings

Here we see > being used a shell prompt, whereas > is also used to redirect output. Similarly, $ is used as a shell prompt, but, as we saw earler, 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 to redirect output or get the value of a variable.

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 1141.jpg 1142.jpg
do
    echo $x
done

or:

for temperature in 1141.jpg 1142.jpg
do
    echo $temperature
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.

Spaces in Names

Whitespace is used to separate the elements on the list that we are going to loop over. If on the list we have elements with whitespace we need to quote those elements and our variable when using it. Suppose our data files are named:

red dragon.dat
purple unicorn.dat

We need to use

for filename in "red dragon.dat" "purple unicorn.dat"
do
    head -n 100 "$filename" | tail -n 20
done

It is simpler just to avoid using whitespaces (or other special characters) in filenames.

Going back to our original file copying problem, we can solve it using this loop:

for filename in *.jpg
do
    cp $filename original-$filename
done

This loop runs the cp command once for each filename. The first time, when $filename expands to 1141.jpg, the shell executes:

cp 1141.jpg original-1141.jpg

The second time, the command is:

cp 1142.jpg original-1142.jpg

Since the cp command does not normally produce any output, it’s hard to check that the loop is doing the correct thing. By prefixing the command with echo it is possible to see each command as it would be executed. The following diagram shows what happens when the modified script is executed, and demonstrates how the judicious use of echo is a good debugging technique.

For Loop in Action

Nelle’s Pipeline: Processing Files

Add additonal metadata to the file names more descriptive. Let’s say we’re interested in catagorizing the images by whether they were origionally mounted in a glass enclosure. This is noted in the slide condition field. We’ll add the letter ‘G’ to slides that had the enclosuer and ‘N’ if they did not. We’ll use ‘X’ instead if there was uneven dye fading. 1411,1143,1148,1149 get G 1142 gets X Everything else gets N

There is probably a more efficient strategy - but start mby appending N to all files with. Then manually change the others to G and X.

Check that imagestats is present in your directory. If not, open a test editor and type

nano imagestats

echo $1 > $2

Nelle is now ready to process her data files. Since she’s still learning how to use the shell, she decides to build up the required commands in stages. Her first step is to make sure that she can select the right files — remember, these are ones whose names end in ‘G’ or ‘N’, rather than ‘X’. Starting from her home directory, Nelle types:

$ cd photos/19
$ for datafile in *[GN].jpg
> do
>     echo $datafile
> done

Her next step is to decide what to call the files that the imagestats analysis program will create. Prefixing each input file’s name with “stats” seems simple, so she modifies her loop to do that:

$ for datafile in *[GN].jpg
> do
>     echo $datafile stats-$datafile.txt
> done

She hasn’t actually run imagestats yet, but now she’s sure she can select the right files and generate the right output filenames.

Typing in commands over and over again is becoming tedious, though, and Nelle is worried about making mistakes, so instead of re-entering her loop, she presses the up arrow. In response, the shell redisplays the whole loop on one line (using semi-colons to separate the pieces):

$ for datafile in *[GN].jpg; do echo $datafile stats-$datafile.txt; done

Using the left arrow key, Nelle backs up and changes the command echo to bash imagestats:

$ for datafile in *[GN].jpg; do bash imagestats $datafile stats-$datafile.txt; done

When she presses Enter, the shell runs the modified command. However, nothing appears to happen — there is no output. After a moment, Nelle realizes that since her script doesn’t print anything to the screen any longer, she has no idea whether it is running, much less how quickly. She kills the running command by typing Ctrl-C, uses up-arrow to repeat the command, and edits it to read:

$ for datafile in *[GN].txt; do echo $datafile; bash imagestats $datafile stats-$datafile; done

Beginning and End

We can move to the beginning of a line in the shell by typing Ctrl-A and to the end using Ctrl-E.

When she runs her program now, it produces one line of output every five seconds or so:

1518 times 5 seconds, divided by 60, tells her that her script will take about two hours to run. As a final check, she opens another terminal window and uses cat to examine one of the output files. It looks good, so she decides to get some coffee and catch up on her reading.

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 Nelle types this:

$ history | tail -n 5
  456  ls -l NENE0*.txt
  457  rm stats-NENE01729B.txt.txt
  458  bash imagestats NENE01729B.txt stats-NENE01729B.txt
  459  ls -l NENE0*.txt
  460  history

then she can re-run imagestats on NENE01729B.txt simply by typing !458.

Other History Commands

There are a number of other shortcut commands for getting at the history.

Variables in Loops

This exercise refers to the data-shell/molecules directory. ls gives the following output:

cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb

What is the output of the following code?

for datafile in *.pdb
do
    ls *.pdb
done

Now, what is the output of the following code?

for datafile in *.pdb
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 *.pdb within the loop body (as well as before the loop starts) to match all files ending in .pdb and then lists them using ls. The expanded loop would look like this:

for datafile in cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb
do
	ls cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb
done
cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb
cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb
cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb
cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb
cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb
cubane.pdb  ethane.pdb  methane.pdb  octane.pdb  pentane.pdb  propane.pdb

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 using ls.

cubane.pdb
ethane.pdb
methane.pdb
octane.pdb
pentane.pdb
propane.pdb

Saving to a File in a Loop - Part One

In the same directory, what is the effect of this loop?

for species in *.pdb
do
    echo $species
    cat $species > alkanes.pdb
done
  1. Prints cubane.pdb, ethane.pdb, methane.pdb, octane.pdb, pentane.pdb and propane.pdb, and the text from propane.pdb will be saved to a file called alkanes.pdb.
  2. Prints cubane.pdb, ethane.pdb, and methane.pdb, and the text from all three files would be concatenated and saved to a file called alkanes.pdb.
  3. Prints cubane.pdb, ethane.pdb, methane.pdb, octane.pdb, and pentane.pdb, and the text from propane.pdb will be saved to a file called alkanes.pdb.
  4. None of the above.

Solution

  1. The text from each file in turn gets written to the alkanes.pdb file. However, the file gets overwritten on each loop interation, so the final content of alkanes.pdb is the text from the propane.pdb file.

Saving to a File in a Loop - Part Two

In the same directory, what would be the output of the following loop?

for datafile in *.pdb
do
    cat $datafile >> all.pdb
done
  1. All of the text from cubane.pdb, ethane.pdb, methane.pdb, octane.pdb, and pentane.pdb would be concatenated and saved to a file called all.pdb.
  2. The text from ethane.pdb will be saved to a file called all.pdb.
  3. All of the text from cubane.pdb, ethane.pdb, methane.pdb, octane.pdb, pentane.pdb and propane.pdb would be concatenated and saved to a file called all.pdb.
  4. All of the text from cubane.pdb, ethane.pdb, methane.pdb, octane.pdb, pentane.pdb and propane.pdb would be printed to the screen and saved to a file called all.pdb.

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 the cat command has been redirected, nothing is printed to the screen.

Limiting Sets of Files

In the same directory, what would be the output of the following loop?

for filename in c*
do
    ls $filename 
done
  1. No files are listed.
  2. All files are listed.
  3. Only cubane.pdb, octane.pdb and pentane.pdb are listed.
  4. Only cubane.pdb is listed.

Solution

4 is the correct answer. * matches zero or more characters, so any file name starting with the letter c, followed by zero or more other characters will be matched.

How would the output differ from using this command instead?

for filename in *c*
do
    ls $filename 
done
  1. The same files would be listed.
  2. All the files are listed this time.
  3. No files are listed this time.
  4. The files cubane.pdb and octane.pdb will be listed.
  5. Only the file octane.pdb will be listed.

Solution

4 is the correct answer. * matches zero or more characters, so a file name with zero or more characters before a letter c and zero or more characters after the letter c will be matched.

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 file in *.pdb
do
  analyze $file > analyzed-$file
done

What is the difference between the two loops below, and which one would we want to run?

# Version 1
for file in *.pdb
do
  echo analyze $file > analyzed-$file
done
# Version 2
for file in *.pdb
do
  echo "analyze $file > analyzed-$file"
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.

The first version redirects the output from the command echo analyze $file to a file, analyzed-$file. A series of files is generated: cubane.pdb, ethane.pdb etc.

Try both versions for yourself to see the output! Be sure to open the analyzed-*.pdb files to view their contents.

Nested Loops

Suppose we want to set up 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 cubane ethane methane
do
    for temperature in 25 30 37 40
    do
        mkdir $species-$temperature
    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 temperatures, and creates a new directory for each combination.

Try running the code for yourself to see which directories are created!

Key Points