Why do we write `while IFS= read -r line`? What does each part do?
IntermediateConceptVariables, quoting and expansions
Answer
IFS=for thisreadonly, so leading and trailing whitespace is kept (important for YAML, Makefiles and indented logs).-rtreats backslashes literally instead of as escape characters (Windows paths, regexes).readreturns non-zero at end of file, which ends the loop.
while IFS= read -r line || [[ -n "$line" ]]; do
printf '%s\n' "$line"
done < /etc/hosts
The || [[ -n "$line" ]] handles a final line with no trailing newline, which read would otherwise drop.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate