Interview Prep/Shell Scripting/Arrays, conditionals and loops

Why is `for line in $(cat file)` wrong?

IntermediateConceptArrays, conditionals and loops
Answer

The command substitution is unquoted, so it is split on every space, tab and newline (not just lines) and each word is glob-expanded. A line ERROR disk * full becomes four iterations, one of which expands to every filename in the current directory.

while IFS= read -r line; do
  process "$line"
done < file

ShellCheck flags this pattern as SC2013 ("To read lines rather than words, pipe/redirect to a 'while read' loop").

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops