Interview Prep/Shell Scripting/Variables, quoting and expansions

Why do we write `while IFS= read -r line`? What does each part do?

IntermediateConceptVariables, quoting and expansions
Answer
  • IFS= for this read only, so leading and trailing whitespace is kept (important for YAML, Makefiles and indented logs).
  • -r treats backslashes literally instead of as escape characters (Windows paths, regexes).
  • read returns 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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions