Yes. command substitution removes every trailing newline1.
To work around it:
var=$(xsel --clipboard; echo .)
var=${var%?}
That is add .\n
to that output. And remove the dot afterwards with ${var%?}
(the \n
is taken care of by the command substitution).
Note that except with zsh
, shell variables can't contain NUL bytes.
If you want to preserve the exit status:
var=$(xsel --clipboard; ret=$?; echo .; exit "$ret")
ret=$?
var=${var%?}
Remember to quote $var
when expanding it:
printf %s "$var"
A helper function:
cmdsubst() {
_var=$1; shift
eval "$_var="'$("$@"; ret=$?; echo .; exit "$ret")
_ret=$?
'"$_var=\${$_var%?}"
return "$_ret"
}
To be used as:
cmdsubst var xsel --clipboard
To preserve the "bold"... Some tools export the CLIPBOARD selection as text/html in addition to just a UTF8 string. In that case (with recent versions of xclip
), you can do:
cmdsubst html xclip -sel c -o -t text/html
See the output of xclip -sel c -o -t TARGETS
to see what selection targets the current owner of the CLIPBOARD selection provides.
Example after copying a part of my comment to Mikel above in iceweasel:
$ xclip -sel c -o -t TARGETS
TIMESTAMP
TARGETS
MULTIPLE
SAVE_TARGETS
text/html
text/_moz_htmlcontext
text/_moz_htmlinfo
UTF8_STRING
COMPOUND_TEXT
TEXT
STRING
text/x-moz-url-priv
$ xclip -sel c -o -t text/html
<span class="comment-copy"><i>should</i> remove <i>only one</i> trailing newline</span>
$ xclip -sel c -o -t TEXT
should remove only one trailing newline
1 An exception to that are the shells of the rc
family where you can say you don't want any post-processing with the var = ``(){xsel --clipboard}
syntax.
$(...)
in shell, the same wayvar=$(echo hello)
has no trailing newline. – Mikel Mar 21 '14 at 13:37