The Internal Field Separator
Explore how the Internal Field Separator (IFS) affects Bash scripting, especially in loops handling filenames with spaces. Learn to adjust IFS and use find and xargs with the NUL byte to create more reliable scripts. This lesson helps you avoid common errors caused by spaces in filenames and enhances your scripting skills.
How Important is this Lesson?
Learning this concept will save you a great deal of time trying to figure out why your for loop is not working as expected, and will help you write more correct bash scripts that won’t fail.
Files With Spaces
Create a couple of files with spaces in their names:
Note that you have to quote the filename to get the spaces in.
Without the quotes, bash treats the space as a token separator.
This means that it would treat the redirection as going to
the file Spaces and not know what to do with the in and
filenameN.txt tokens.
Now if you write a for loop over these files that just runs ls
on each file in turn, you might not get what you expect.
Type this in and see what happens:
Hmmm. The for loop has treated every word in the filenames as a
separate token to look for with ls.
In other words, bash has treated each space ...