Bash Script Use IFS in For Loops: 5 Easy Fixes
A bash script use IFS question usually starts with one idea: the Internal Field Separator decides how the shell splits text into words. The old version of this post gave six examples. Run in Bash 5.2.37 on Debian 13, the first one works, three others behave differently from what the text promises, and the last one works only by accident. This rewrite shows the real output of each example and the safe form that you should use instead.
Contents
- Bash script use IFS: how splitting happens
- Bash script use IFS to read a file line by line: for versus while read
- Bash script use IFS for CSV files: set IFS only for read
- Bash script use IFS in nested loops with two values
- Bash script use IFS: quoting, key:value and a few more facts
- Common mistakes in a bash script use IFS
- A short checklist before you write a bash script use IFS
- FAQ
Bash script use IFS: how splitting happens
IFS applies when the shell expands an unquoted variable or command substitution, and when read splits a line. The first example of the old post set IFS=$'\n':,' '. The lab dumped the value with od -c: newline, colon, comma and space, four characters. The string huu:phan linux operating,system was then split into huu, phan, linux, operating and system, as the old output claimed. One more fact: with a quoted string, as in for entry in "huu:phan ...", the loop runs once, and the inner for value in $entry is the loop that really splits. The outer loop adds nothing.
Bash script use IFS to read a file line by line: for versus while read
The old advice was IFS=$'\n'; for line in $(cat example.txt). With a file of three lines (one with double spaces, one with the text *.txt literal) and two files a.txt and b.txt in the folder, it printed the three lines unchanged. The danger is in what happens when IFS is not set: the same loop printed ten items (line, one, line, two, with, spaces, a.txt, b.txt, example.txt, literal), and the pattern *.txt was replaced by the names of the files in the directory. Command substitution splits and also expands wildcards. The loop that has neither problem is:
while IFS= read -r line; do
echo "[$line]"
done < example.txt
It printed the three lines exactly, with the double spaces kept and *.txt literal untouched. IFS= keeps leading and trailing spaces, and -r keeps backslashes.

Bash script use IFS for CSV files: set IFS only for read
The old CSV example assigned IFS=',' for the rest of the script. Two problems showed up. A later loop over files="one two three" printed one item, item [one two three], because the space was no longer a separator. And the quoted CSV row 1,"x,y",3 was cut at the comma inside the quotes: Column 2: "x, Column 3: y",3. The second problem remains with the better form; IFS cannot understand CSV quoting. Use it only for simple files without quoted commas. Put the assignment in front of read, so it affects only that command:
while IFS=',' read -r col1 col2 col3; do
echo "[$col1][$col2][$col3]"
done < data.csv
This printed [a][b][c], [1]["x][y",3] and [][][last]: empty fields are kept. Another trap is a last line without a newline. With input printf '1,2,3' the while read loop did not run at all, because read returns failure at the end of input. Add || [ -n "$col1" ] to the loop condition if your files may end without a newline.
Bash script use IFS in nested loops with two values
The nested example of the old post is meant to split row1:val1,val2;row2:val3,val4 into rows and then into values. The real output was Processing row1:val1,val2;row2:val3,val4, then Value: row1:val1,val2 and Value: row2:val3,val4. The outer loop expanded $data with the default IFS and got one word; the commas were never used. The assignments inside the loop run too late for the expansions that already happened. Split in two stages with read -a instead:
IFS=';' read -r -a rows <<< "$data"
for row in "${rows[@]}"; do
name=${row%%:*}; vals=${row#*:}
IFS=',' read -r -a values <<< "$vals"
echo "$name -> ${values[*]} (${#values[@]} values)"
done
It printed row1 -> val1 val2 (2 values) and row2 -> val3 val4 (2 values).
Bash script use IFS: quoting, key:value and a few more facts
- With
IFS=',',for item in "$string"printed one item[a,b,c], and the unquoted form printed[a],[b],[c]. Quoting prevents the split, so the old tip to quote variables "when using IFS" is the opposite of what a splitting loop needs. "${arr[*]}"joins array elements with the first IFS character: it printedx,y,z, while"${arr[@]}"printedx y z.- The old key:value example printed
name is John,age is 30andcity is New York. It works, but it changes IFS inside the loop without restoring it. The cleaner form sets it for each read:IFS=':' read -r key value <<< "$entry", with the same output. - In dash (
sh) the formIFS=$'\n'is not supported: the lab printedIFS=[$\n], the two literal characters. See the portable shell scripts post.
Common mistakes in a bash script use IFS
- Leaving IFS changed for the whole script, or restoring it with a typed value instead of saving the old one.
- Using
for x in $(cat file), which splits on spaces and expands wildcards. - Expecting IFS to parse quoted CSV.
- Assigning IFS inside a loop and expecting an expansion that already happened to change.
For other loop and debugging habits, see the script debugging post. The rules for word splitting are in the Bash manual.
A short checklist before you write a bash script use IFS
Ask these three questions first. Is the text a file, a string or an array? For a file, use while IFS= read -r. For a string with one known separator, use IFS=sep read -r -a array <<< "$string", then loop over "${array[@]}". Does the data allow quoted separators, such as a comma inside quotes? Then IFS is the wrong tool and you need a CSV parser. Finally, run the script once with a file that has spaces, a wildcard character and no final newline, because those three cases broke the old examples.
FAQ
How do I restore IFS after a bash script use IFS change? Save it first, as in the old example (IFSOLD=$IFS), or limit the change to one command with IFS=x read ..., which needs no restore.
Does a bash script use IFS the same way in every shell? No. The lab only tested Bash for the examples and dash for the $'\n' form.
Comments
Post a Comment