Frequently Asked Question
What is IFS and what are the common pitfalls?
IFS is the Internal Field Separator, the variable that tells bash which characters
to break on during word splitting and during read. Its default value is space, tab,
and newline, which is why unquoted variables get chopped at whitespace. You can change
it to split a string by a different delimiter: IFS=',' read -ra fields <<< "a,b,c"
reads three comma-separated values into the fields array. After such a manipulation
it is good practice to restore IFS to its default with IFS=$' \t\n', especially in
functions, to avoid surprising the caller.
The classic pitfall in reading files is forgetting IFS= (empty) on the read line:
while read -r line strips leading and trailing whitespace from each line, mangling
indented content; while IFS= read -r line preserves it. The -r flag is equally
important, it stops read interpreting backslashes as escape characters, which would
otherwise corrupt any line containing a literal backslash. Together, while IFS= read -r line; do ...; done < file is the only correct way to iterate a file line by line
in bash.