1

Below is my toy program

xxxx@xxxx-Dell:~/Desktop$ foo=$'line1\nline2'
xxxx@xxxx-Dell:~/Desktop$ echo $foo
line1 line2
xxxx@jxxxx-Dell:~/Desktop$ echo "$foo"
line1
line2

I know quoting mechanism in shell command language. My expectation is two echo command would output same thing, as dollar sign is a meta-chracters anyway in plaintext and double qouting. So why is it different. Is it some nested qutation?

nathan
  • 754
  • 1
  • 10
  • 24
  • 1
    @DevNull Thanks, I knew this way. My real issue is why echo $foo and echo "$foo" behaves differently here – nathan Dec 06 '16 at 03:44
  • Ahh, after viewing the accepted answer, I see what you were looking for. Well, glad it worked itself out. Cheers! – Cloud Dec 07 '16 at 04:35

1 Answers1

3

The difference between the quoted and unquoted versions may depend on your shell, but most likely is:

  • quoted, "$foo" represents a single argument which is passed to the echo command, which prints it verbatim, followed by a newline.
  • unquoted, $foo expands to a set of arguments separated by $IFS. If $IFS is unset, it defaults to whitespace, and if there is no field separator, you have just one field.

In the unquoted version, there's no reason to expect that the newline will be considered a part of the output, as it isn't even really part of the input to the echo command. It simply separates arguments.

If you want to change this behaviour, you could change your $IFS setting, but I don't recommend it. Change IFS when you need to process fields, not to format your output.

For predictable output, follow the POSIX.1 recommendation, and don't use echo at all. Use printf instead.

ghoti
  • 45,319
  • 8
  • 65
  • 104
  • 1
    It is legit to use `IFS` to format the output as a field separator with array items (`"${array[*]}"`) or `"$*"`, but again that only takes effect inside double quotes. – cdarke Dec 06 '16 at 07:36
  • 2
    @ghoti Thanks so much . I think you are right. I also tried $'line1\tline2', which verified your explaination – nathan Dec 06 '16 at 18:46
  • 1
    FYI, I believe this is official doc. "If a parameter expansion occurs inside double-quotes: Pathname expansion shall not be performed on the results of the expansion. Field splitting shall not be performed on the results of the expansion, with the exception of '@' ; see Special Parameters." – nathan Dec 06 '16 at 18:50