Course / The terminal and the language
Repeat a task for each item
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach 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 submitGoal
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 filetestdata/notes.txt. - Print the
item:lines first, in the order the words were given, then theline:lines in file order. - Use a
forloop over"$@"for the words. Keep the double quotes so a word with spaces stays in one piece. - Use a
whileloop withIFS= read -r linefor the file, and feed it with< testdata/notes.txtafterdone. - Print with
printf, using%sfor the word or line. - If no words are given, print no
item:lines. If the file is empty, print noline: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
- You need two loops, one after the other. A
forloop goes over"$@"(the arguments). Awhileloop reads the file. - For the file, use
while IFS= read -r line; do ... done < testdata/notes.txt. The< filegoes afterdone.IFS=and-rkeep the line exactly as written. for word in "$@"; do printf 'item: %s\n' "$word"; done, thenwhile IFS= read -r line; do printf 'line: %s\n' "$line"; done < testdata/notes.txt, written across several lines.