A senior administrator runs a script that processes a CSV file. The script contains the following snippet: 'for field in $(cat data.csv); do ...'. The data.csv file contains lines like: 'John Doe, 123 Main St, Springfield'. The script fails to process correctly, splitting fields incorrectly and causing errors. Which of the following is the most appropriate fix?
Reads each line correctly with IFS= to preserve whitespace.
Why this answer
The script fails due to word splitting and globbing when iterating over the output of `cat data.csv` with a `for` loop. Using `while IFS= read -r line` reads each line verbatim, preserving spaces and commas, and is the standard pattern for processing CSV or delimited files line by line in bash.
Exam trap
The trap here is that candidates often think quoting the command substitution or using `xargs` will fix the splitting issue, but they fail to recognize that `for` inherently splits on IFS, whereas `while read` processes one line at a time without word splitting.
How to eliminate wrong answers
Option A is wrong because `xargs` by default splits input on whitespace and newlines, which would still break fields containing spaces like 'John Doe' and does not address the core issue of reading entire lines. Option B is wrong because `$(<data.csv)` is equivalent to `$(cat data.csv)` and still undergoes word splitting and globbing, so fields with spaces or special characters are incorrectly split. Option C is wrong because double quotes around the command substitution `"$(cat data.csv)"` would treat the entire file as a single string, causing the loop to iterate only once over the whole file content, not per line.