Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo "string" | xclip -selection clipboard , copies the 'string' but also adds a new line to it. how to fix this?

echo -n "string" | xclip -selection clipboard

I should probably have elaborated a bit. The default for echo is to output the string AND a newline. -n suppreses the latter.


The more generic solution is to ignore new lines regardless of the input source. For instance, the common use case is to copy to the clipboard a path of the current directory. The command

pwd | xclip -selection clipboard

copies the new line character and this is often not what we want. The solution is the following:

pwd | xargs echo -n | xclip -selection clipboard

You can create an alias to make it more convenient:

alias xclip='xargs echo -n | xclip -selection clipboard'

and from now on use:

pwd | xclip # copied without new line
echo "foo" | xclip # copied without new line

Since version 0.13 of xclip, you have a generic way that will preserve the inner new lines with the option r or rmlastnl.

So you will have:

pwd | xclip -r # copied without new line
echo "foo" | xclip -r # copied without new line
ps | xclip -r # copied without the last new line!