Internal Field Separator
Thanks to some anonymous reader in barrapunto i realized that my bash script that list a directory structure into a html file did not work with filenames that have spaces on them, and that didn’t work because of the Internal Field Separator. $IFS is a variable that the shell uses to determine boundaries between words when it interprets character strings. $IFS defaults value is the space, tab and new line characters, but it can be changed.
Consider this sequence of variable assignments and for loops:
$ line=some:kind:of:paper
$ for i in $line
> do
> echo $i
> done
some:kind:of:paper
The result will be just one echo showing the string as it is because the “:” character it’s not an Internal Field Separator so let’s change it:
$ OIFS=$IFS
$ IFS=:
$ for i in $line
> do
> echo $i
> done
some
kind
of
paper
Now all the words from that string where separated. Now the $IFS value is “:”, it may be a good idea to set it back to it’s default value. It was a good thing that we save that value on the $OIFS variable so we can just reassign it:
$ IFS=$OIFS
If for some reason we don’t save the value of $IFS before changing it we can change it to it’s default value like this:
$ IFS=$’ \t\n’
where the blank space “ “ refers to a space, the “\t” to a tab and “\n” to a new line.
Today we all learned about the $IFS variable, and the script dir2html.sh now works just fine.
0 comments
