Why does read add newline with default IFS and a single variable?

I was experimenting with IFS and read. I tried the following and I can't get my head around why it resulted this way:

$ IFS=$' \t\n'
$ read a <<< "the plain gold ring"
$ printf "=%s=\n" $a
=the=
=plain=
=gold=
=ring=
  1. Is a an array now? Or is it a string?
  2. Why did read add newline between two words?
  3. Why is printf printing as if it is inside a loop?

I actually expected no separation would occur because I am reading into a single variable a only.

0

1 Answer

  1. Is a an array now? Or is it a string?

It's a string. You told read to read to a single variable, the entire string was stored as a. If the command was read a b c <<< …, then a would get the, b would get plain and c would get gold ring.

  1. Why did read add newline between two words?

It didn't, printf did because you told it to. Run echo $a.

  1. Why is printf printing as if it is inside a loop?

Because $a expands to multiple words. The format you provided expects one string, it gets many. With too many arguments printf loops. Compare printf "=%s=\n" "$a" where "$a" is a single argument to printf.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like