43

this is the command responsible for adding a new line to the string

echo "string" | xclip -selection clipboard
2
  • Suggest editing the title of this question to something like 'Prevent xclip from appending newline.' It's a great question, it was just hard to find!
    – cydonian
    Oct 17, 2013 at 19:33
  • Good question, thanks! Nov 6, 2019 at 11:26

3 Answers 3

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

2
  • 2
    if you wish to copy current path echo -n $(pwd) | xclip -selection clipboard Apr 28, 2017 at 9:21
  • one improvement for previous command echo -n ${PWD/ /\\ } | xclip -selection clipboard backslashes white spaces Apr 28, 2017 at 9:32
33

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
3
  • how does adding pwd make this "more generic"? :)
    – tink
    Nov 28, 2018 at 18:25
  • 4
    If you read carefully, you can see that the generic solution refers to "ignore new lines regardless of the input source". The pwd part is shown as an example and "common use case" why you may want to do it. The last example uses echo as well. Dec 1, 2018 at 16:17
  • And what suggests to you that one wants to get rid of ALL newlines? (pwd; pwd)| xargs echo -n | xclip -selection clipboard
    – tink
    Apr 16, 2022 at 18:23
22

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!
4
  • Requires version 0.13 though
    – ricab
    Jun 13, 2017 at 20:01
  • Thanks. I will add that in my answer.
    – rools
    Jun 14, 2017 at 8:33
  • 2
    the -r did the trick fro me. would have helped if i fully read the man
    – 4UmNinja
    Dec 4, 2021 at 10:34
  • 1
    It's been a while since xclip 0.13. This should be the accepted answer and people should update.
    – N1ngu
    Jan 4 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.