Robust Scripts
Reading Lines
Preserving Text
Line-oriented scripts need to keep the text exactly as it arrives. IFS= read -r is the usual safe loop shape.
Program
Play the script to watch two input lines update the loop variables without losing the embedded space.
read_lines.sh
#!/usr/bin/env bash
count=0
last=""
while IFS= read -r line; do
count=$((count + 1))
last="$line"
done <<'DATA'
alpha
two words
DATA
echo "$count:$last"
read -r
`read -r` reads a line without treating backslashes as escape characters.
IFS=
`IFS=` keeps leading and trailing whitespace from being trimmed before assignment.
here document
`<<'DATA'` feeds literal lines to the loop until the closing marker.