Skip to content

Loops: do the same thing to every file

AdvancedLesson 34 of 668 min

Back up every config file with a for loop and read a list line by line with while read. Learn why quotes matter, in a practice terminal in your browser.

Before an upgrade you want a copy of every config file. Three files, you'd copy by hand. Thirty, and you'd want the shell to do it. That's what loops are for.

for

for takes a name and a list, and runs the commands between do and done once for each item, with the name set to it:

for fruit in apple pear fig; do echo "I like $fruit"; done
for f in config/*.conf; do echo "found $f"; done
for n in {1..3}; do echo "round $n"; done

The list can be words, a wildcard, a range in braces, or the output of a command in $( ). On one line, separate the parts with ;. In a script, put each part on its own line:

for f in config/*.conf; do
  cp "$f" "$f.bak"
done

Quote the variable

Always write "$f", with the quotes. A file called my notes.txt would otherwise reach cp as two words, my and notes.txt, and the copy would fail, or worse, copy the wrong thing.

while read: one line at a time

for splits its list at every space, which breaks lines like "Ana Lima" in two:

for name in $(cat team.txt); do echo "Hello, $name"; done

To go through a file line by line, use while read. read takes one line of input into a variable, and the loop stops when there are no lines left. The < team.txt at the end feeds the file in:

while read -r name; do echo "Hello, $name"; done < team.txt

-r keeps any backslashes in the line as they are; use it every time.

while

while on its own repeats as long as a command works, which is handy for counting or waiting:

n=1; while [ $n -le 3 ]; do echo "try $n"; n=$((n + 1)); done

Your turn

Two jobs, each with a loop. (1) Make a backup of every .conf file in config, next to it, with .bak added to the name (app.conf → app.conf.bak). (2) For each person in team.txt, make a folder under ~/team named exactly as their full name, such as team/Ana Lima.

Next