Course outline
Course / The terminal and the language

Repeat a task for each item

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/04-04-shell-for-and-while-loops
cd 04-04-shell-for-and-while-loops
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Your script is started with some words as arguments, like sh answer.sh red "blue green". Print each argument on its own line as item: WORD, then print each line of testdata/notes.txt as line: TEXT.

Example

Started as sh answer.sh red "blue green", with a testdata/notes.txt that holds:

first note
second  note

the script prints:

item: red
item: blue green
line: first note
line: second  note

"blue green" is one argument, so it gets one item: line. A line from the file keeps its own spaces, including two spaces in a row.

Rules

  • Edit answer.sh. It gets the words as arguments and reads the file testdata/notes.txt.
  • Print the item: lines first, in the order the words were given, then the line: lines in file order.
  • Use a for loop over "$@" for the words. Keep the double quotes so a word with spaces stays in one piece.
  • Use a while loop with IFS= read -r line for the file, and feed it with < testdata/notes.txt after done.
  • Print with printf, using %s for the word or line.
  • If no words are given, print no item: lines. If the file is empty, print no line: lines. Both can happen at once, and then your script prints nothing at all.
  • A blank line in the file prints line: with nothing after it.
  • Every line in the file ends with a newline. Do not edit testdata/notes.txt; your script only prints.
  • Do not type the sample words or sample lines into the script. The test uses different ones.

What you'll practice

for loops over "$@", while with read, IFS= and -r, redirecting a file into a loop, and printf with %s.

Run it

gonomicon fetch week-1/04-04-shell-for-and-while-loops
cd 04-04-shell-for-and-while-loops
gonomicon test
gonomicon submit

Hints

  1. You need two loops, one after the other. A for loop goes over "$@" (the arguments). A while loop reads the file.
  2. For the file, use while IFS= read -r line; do ... done < testdata/notes.txt. The < file goes after done. IFS= and -r keep the line exactly as written.
  3. for word in "$@"; do printf 'item: %s\n' "$word"; done, then while IFS= read -r line; do printf 'line: %s\n' "$line"; done < testdata/notes.txt, written across several lines.

Something wrong with this lesson? Report a problem