0

Why <<<$x removes new line char?

> cat <<<"A
B" # prints two lines (as expected)
A
B

> x="A
B"
> cat <<<"$x" # prints two lines (again, as expected)
A
B

> cat <<<$x # prints one line (..Why only one line!? I would expected two lines, or just "A", or error; Who's eating up the new line?)
A B

How come did the new line disappear? Is it convenience thingy specially for <<<? Are there other situations where similar thing happen? (apart from <<<$var)

Nothing relating to new lines in here: https://www.tldp.org/LDP/abs/html/x17837.html (if relevant: GNU bash, version 4.2.46(2)-release)

IndustryUser1942
  • 1,052
  • 1
  • 8
  • 12
  • 2
    It undergoes word splitting, therefore you lose the whitespaces. In future versions of bash, variables that are part of here-strings no longer undergo word-splitting, but in version 4.2, they still do. – PesaThe Jul 09 '20 at 12:20
  • @PesaThe Please paste your first comment as an answer (i.e. version specific behavior, of word splitting) - I'll mark accepted. Anyway: is it special/scoped word splitting? With "usual" word splitting: `f="long name"; touch $f` creates two files, because command was `touch long name`. If `<<<` would use usual word splitting, then `x="A B"; cat <<<$x` would run command `cat << – IndustryUser1942 Jul 09 '20 at 12:39
  • `<<< word` redirects the `word` to stdin. You can sort of imagine it as doing `echo $x | cat`. – PesaThe Jul 09 '20 at 12:43
  • 1
    Here is a related question I once had where the specific versions are mentioned https://stackoverflow.com/questions/47744854/do-here-strings-undergo-word-splitting – PesaThe Jul 09 '20 at 12:50
  • 1
    `bash` 4.2 had issues with unquoted here-strings. `$x` wasn't *supposed* to undergo word-spitting, but it did. The issue is fixed to some extent in 4.3 and more completely in 4.4. – chepner Jul 09 '20 at 12:52

0 Answers0