2

I see following code in a script:

OLD_IFS="$IFS"
IFS='something-special'
# code that needs the special IFS
# ...
IFS="$OLD_IFS"

If the IFS is not set before the script fragment then the script sets it to an empty string and the empty IFS and undefined IFS are different.

The script probably assume the IFS is always set. Is it safe to make such assumption?

Kusalananda
  • 333,661

1 Answers1

3

Yes, it is safe to assume that IFS is set.

The default value of IFS is a string consisting of a space, a tab, and a newline. This is a requirement of the POSIX standard:

The shell shall set IFS to <space> <tab> <newline> when it is invoked.

In a bash shell with default settings, printf '%q\n' "$IFS" will show the default value of IFS as

$' \t\n'

It is unsafe to assume that IFS has the default value, and it's important to properly quote expansions so that field-splitting does not occur. It's extra fun to consider what happens if IFS contains digits.

See also

Kusalananda
  • 333,661
  • An answer on my suggested dupe says otherwise. (Unless you're talking specifically about bash because this is tagged [tag:bash], but then you do mention POSIX, so ...). – muru May 21 '18 at 06:53
  • @muru That answer says that IFS may possibly not be inherited from the parent environment, in which case it will be set to space-tab-newline. If is inherited, it may obviously have another value. – Kusalananda May 21 '18 at 06:55
  • 1
    @Inian Added that. – Kusalananda May 21 '18 at 06:59