Lone Learner
Lone Learner

Reputation: 20688

Difference in behaviour between whitespace in IFS vs. non-whitespace in IFS

I know that read command splits the input by the characters in the IFS. So if I set IFS as a space then input to the read command is split using space as the delimiter. This is shown below.

[lone@centos ~]$ IFS=" "
[lone@centos ~]$ read a b c
 foo bar baz qux
[lone@centos ~]$ echo "$a"
foo
[lone@centos ~]$ echo "$b"
bar
[lone@centos ~]$ echo "$c"
baz qux

I was expecting that if I make change the IFS to a non-whitespace character, say, a colon and use colon as delimiter in my input, there should be no change in behaviour. But this turned out to be wrong. For example, in the output below, echo "$a" is blank. Why?

[lone@centos ~]$ IFS=:
[lone@centos ~]$ read a b c
:foo:bar:baz:qux
[lone@centos ~]$ echo "$a"

[lone@centos ~]$ echo "$b"
foo
[lone@centos ~]$ echo "$c"
bar:baz:qux
[lone@centos ~]# echo $c
bar baz qux

And why does the output of echo $c does not contain the colons?

Upvotes: 2

Views: 116

Answers (1)

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45636

Question 1: In the output below, echo "$a" is blank. Why?

Because whitespace is special as defined in POSIX (2.6.5 Field Splitting):

3a. IFS white space shall be ignored at the beginning and end of the input.

Question 2: And why does the output of echo $c does not contain the colons?

Because bash performs word splitting in accordance with IFS (which is still set to :) before passing bar, baz and qux as separate arguments to echo.

Upvotes: 1

Related Questions