Loops: do the same thing to every file
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"; donefor f in config/*.conf; do echo "found $f"; donefor n in {1..3}; do echo "round $n"; doneThe 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"; doneTo 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)); doneYour 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.
Your task
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.
- Every .conf file has a .bak copy (not done yet)
- A folder for each person, with their full name (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
for- for NAME in LIST; do …; done runs the commands once for each word in the list
while read- Reads input one line at a time into variables and runs the loop once per line
while- while COMMAND; do …; done repeats the commands as long as COMMAND works
Every everyday command on one page: the Linux commands cheat sheet.