How do you loop over lines of a file safely in bash?
⚡
Quick Answer
Use `while IFS= read -r line; do ... done < file` to preserve whitespace and backslashes.
Detailed Answer
for line in $(cat file) word-splits and glob-expands — wrong for lines with spaces. while IFS= read -r line reads one line at a time without trimming whitespace (IFS=) or mangling backslashes (-r). It's the correct idiom for line processing.
Code Example
while IFS= read -r line; do echo "$line"; done < input.txt
💡
Interview Tip
Know why for-in-cat is an anti-pattern.
bashreadloops