The Internal Field Separator
In this lesson we will cover how and when to use the 'IFS' variable to protect your scripts from bugs, as well as other techniques available to achieve similar ends.
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:
echo file1 created > "Spaces in filename1.txt"cat "Spaces in filename1.txt"echo file2 created > "Spaces in filename2.txt"cat "Spaces in filename2.txt"
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:
for f in $(ls)dols $fdone
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 ...