IFS null is not the same as unset IFS?
The answers you found on Stack Exchange are right and this tutorial is wrong. You can experiment by yourself or look it up in the standard. An unset IFS
is equivalent to setting it to the default value of space-tab-newline, while an empty IFS
effectively turns off field splitting.
You can consult Sven Mascheck's page on IFS about historical implementations. A few historical shells didn't like unset IFS
, and a very old version of ksh treated it like an empty IFS
but all modern shells and most old shells treat an unset IFS
like the default value.
You should not start your script with IFS=
unless you want to turn off field splitting (which can be a reasonable decision — but note that you still need to put double quotes around substitutions to avoid globbing, unless you turn that off with set -f
too). To reset the default value, use unset IFS
. It's debatable whether this is useful at the beginning of a script; there are plenty of other bad things such as a dodgy PATH
that the caller can do to make your script go wrong.
This tutorial also advises to reset PATH
. This is usually bad advice. In most cases, you cannot predict what the correct search path is, but the user knows. How do you know whether /usr/local/bin
or /home/bob/bin
contains bug-fixed versions of utilities on an ancient unix where the ones in /usr/bin
are buggy? Do you really want to embed all the logic to figure out whether to put /usr/xpg6/bin
ahead of /bin
? At what position you want /usr/gnu/bin
? Do not reset PATH unless your script targets a specific system.
I haven't read this tutorial, but I did check one thing: it doesn't tell you right from the start to always put double quotes around variable substitutions and command substitutions. So I do not think this tutorial is a good one.
Related videos on Youtube
test
Updated on September 18, 2022Comments
-
test almost 2 years
I read a great question on here called Understanding IFS. I was surprised because the answers and comments quote POSIX which states that IFS= is not the same as unsetting IFS. If you unset IFS, apparently the default value is used. If you make IFS null instead, there is no splitter. I knew I had seen a different take on that, and I found this in my bookmarks:
$IFS
The very first statement in your script should be
IFS=
which resets the input field separator to its default value. Otherwise, you inherit $IFS from the user, who may have set it to some bizarre value in order to make sh parse strings differently from the way you expect, and induce weird behavior.
So was that true some time ago or is the author just wrong?
-
Gilles 'SO- stop being evil' almost 7 years@Melab
unset IFS
does not resetIFS
to its default value, it unsets it. But an unsetIFS
has the same effect asIFS
set to the default value.