04 / DECISIONS AND REPETITION · LESSON 16

Interactive input and while/read

Read a human answer and file lines without losing whitespace or backslashes.

13 min · learn at your pace

Read one line deliberately

IFS= read -r answer reads a line without trimming surrounding whitespace or treating backslashes as escapes. The newline itself is removed. Write a prompt with printf first; the lab then accepts a line in the terminal. Enter can send an empty line, and Ctrl+D signals end of input.

Input answers stay in the current session unless your script explicitly writes them into a file or prints them. Checks supply deterministic input automatically and never ask you to type answers. Stop interrupts the runtime even while it is waiting for input.

A file is a sequence of records

Use while IFS= read -r line || [ -n "$line" ]; do ...; done < file to include a final nonempty line without a trailing newline. The redirection keeps the loop in the current shell; piping into a loop usually puts that loop in a subshell in Bash, so assignments may not survive afterward.

A blank line is still a line. Decide whether to preserve, reject or ignore it. This task preserves every line and counts it, including blank ones. Be equally explicit about an interactive EOF: it is different from a successfully read empty answer.

Try an example.sh
printf 'Name: '
if IFS= read -r name; then printf 'Hello, %s\n' "$name"; else printf 'Input ended\n'; fi
YOUR TURN

Put it into practice.

Print the prompt `Name: ` (no newline), then read one answer with whitespace/backslashes preserved. On EOF print `Input ended` plus newline and exit 0. Otherwise print `Hello, <answer>` plus newline. Also copy every line from `notes.txt` into `numbered.txt` as `index<TAB>line`, preserving blank lines and an unterminated final line, adding a final newline to each output row.

See an explained solution
One way to solve it.sh
printf 'Name: '
if ! IFS= read -r name; then printf 'Input ended\n'; exit 0; fi
printf 'Hello, %s\n' "$name"
index=0
: > numbered.txt
while IFS= read -r line || [ -n "$line" ]; do
    index=$((index + 1))
    printf '%d\t%s\n' "$index" "$line" >> numbered.txt
done < notes.txt

The interactive branch distinguishes EOF from an empty line. File redirection keeps counting in this shell, and the EOF guard preserves the last record.