Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
add comment

2 Answers

up vote 8 down vote accepted

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 susbtitution 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.

share|improve this answer
    
Much more thorough than my answer. –  Mike Sep 6 '11 at 0:02
    
Bash may have borrowed here-strings from ksh93, but ksh in turn borrowed them from zsh, which got them from the Plan 9 shell rc. –  Mark Reed Jan 7 at 22:04
add comment

I think that's the only way to get a newline at the end of a here-string, proof:

xxd <<<`echo -ne "a\n"`

It would appear that the here-string operator strips newlines unless they are given in the syntax you submitted.

share|improve this answer
    
It's the command substitution that's stripping the final newline. You could simplify this to xxd <<<$(echo a). –  Gilles Sep 6 '11 at 0:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.