Course / The terminal and the language
Handle every line as written
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-06-shell-read-lines-safely
cd 04-06-shell-read-lines-safely
gonomicon submitGoal
Read testdata/lines.txt one line at a time and print each line with a > in front of it. Every line must come out exactly as it is in the file: blank lines, spaces at the start or end, and backslashes included.
Example
If testdata/lines.txt held:
first note
indented
C:\temp\new
your script prints:
>first note
>
> indented
>C:\temp\new
The blank line becomes a lone >. The four spaces stay. The backslashes are not turned into anything else.
Rules
- Edit
answer.sh. It reads the filetestdata/lines.txtand prints the result. - Use a
whileloop withIFS= read -r line, and feed the file in with< testdata/lines.txtafterdone. - Print each line with
printf '>%s\n'and"$line"in double quotes. Do not useecho. - Print one output line per input line, in the original order.
- Spaces at the start and end of a line must stay, and so must tabs. Do not trim anything.
- Backslashes must stay exactly as written. This is what
-ris for. - If the file is empty, print nothing at all.
- Every line in the file ends with a newline. Do not edit
testdata/lines.txt; your script only prints. - Do not type the sample lines into the script. The test uses different files.
What you'll practice
while with read, IFS= and -r to keep lines intact, redirecting a file into a loop, quoting "$line", and printf with %s.
Run it
gonomicon fetch week-1/04-06-shell-read-lines-safely
cd 04-06-shell-read-lines-safely
gonomicon test
gonomicon submit
Hints
- Read the file with a
whileloop andread, and feed the file in afterdonewith< testdata/lines.txt. - Plain
readstrips spaces at the edges and treats backslashes as special. Writewhile IFS= read -r line; doso each line arrives exactly as it is in the file. while IFS= read -r line; do printf '>%s\n' "$line"; done < testdata/lines.txt, written across several lines. Keep the double quotes around$line.