Is there any significant difference between these?
cat <<< "one
two
three"
and
cat << END
one
two
three
END
It makes me wonder why here-documents exist, and when should I use one over the other. This worked fine even in sh
(version 5.0.18)
Here documents are much older than here strings; so it's not really meaningful to ask as if they had both been invented at the same time.
In very brief, here documents were a feature of the 1979 original Bourne shell from Unix System V. (I speculate that the feature was descended from or inspired by earlier big-iron batch processing languages, but I'm not familiar enough with them to explore this further.)
Here strings were first introduced in rc
, the Plan 9 shell. It was first published in 1989, though I'm not sure if here strings were a feature of the original version. From there, they were borrowed into ksh
, Bash, and other modern shells; but they are still not available in POSIX sh
.
(Which sh
you found the feature in is unclear - perhaps you could clarify which OS you are using. Some platforms simply use Bash in "POSIX mode" as their sh
implementation; this doesn't entriely disable many Bash features, so perhaps that's what you found.)
The dominating advice, then, is to use here documents in any code which needs to be portable.
Other than that, here strings can feel somewhat more flexible, especially when coupled with the "C-style" string notation in Bash.
cat <<< $'newline\n\ttab'
On the other hand, here documents have some convenience properties such as the ability to permit or disable variable expansion in the here document, and the feature to strip off leading tabs with the <<-delimiter
syntax, with a single dash (minus) before the delimiter after <<
.
cat <<-\eof
(Stack Overflow will convert tabs to spaces,
but imagine that this is indented by a tab.)
The backslash, or any quotes
- single or double -
around the delimiter prevents
$variable, `backtick`, and \backslash processing.
eof
Some users might also find it clunky or unattractive to use literal newlines between quotes (or are unaware that this is allowed).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With