The following examples show that a newline is added to a here-string.
Why is this done?
xxd -p <<<'a' # output: 610a xxd -p <<<'a ' # output: 610a0a
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The easy answer is because ksh is written that way (and bash is compatible). But there’s a reason for that design choice.
Most commands expect text input. In the unix world, a text file consists of a sequence of lines, each ending in a newline. So in most cases a final newline is required. An especially common case is to grab the output of a command with a command susbtitution, process it in some way, then pass it to another command. The command substitution strips final newlines; <<< puts one back.
tmp=$(foo)
tmp=${tmp//hello/world}
tmp=${tmp#prefix}
bar <<<$tmp
Bash and ksh can’t manipulate binary data anyway (it can’t cope with null characters), so it’s not surprising that their facilities are geared towards text data.
The <<< here-string syntax is mostly only for convenience anyway, like << here-documents. If you need to not add a final newline, use echo -n (in bash) or printf and a pipeline.
Method 2
One scenario in which it is practical to have newlines appended to here-strings is when using the read command when set -e mode is active. Recall that set -e causes a script to terminate when it (more or less) encounters statements that generate a non-zero status code. Consider that read generates a non-zero status code when it encounters a string without newlines:
#!/bin/bash set -e # The following statement succeeds because here-strings append a newline: IFS='' read -r <<< 'newline appended' echo 'Made it here' # The following statement fails because 'read' returns a non-zero status # code when no newlines are encountered. printf 'no newline' | IFS='' read -r echo 'Did not make it here'
Method 3
I think that’s the only way to get a newline at the end of a here-string, proof:
xxd <<<`echo -ne "an"`
It would appear that the here-string operator strips newlines unless they are given in the syntax you submitted.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0