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").
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate