2

Is there something I can do so that whenever I pipe something into xclip it does not include a new line at the end?
As a workaround, I am using echo -n $(CMD_TO_COPY) | xclip, but it's kind of annoying having to type all of this each time I want to copy something.

2 Answers 2

5

According to the man page, xclip has a -rmlastnl (-r) option that will do exactly what you want:

echo hello | xclip -i -r
1

Though xclip since version 0.13 does have an option to remove a trailing newline as already noted by larsks, you could also always define a function that does the processing you want like:

clipboard() { printf %s "$(cat -- "$@")" | xclip -sel c; }
clipboard() { printf %s "$(cat -- "$@")" | xsel -b; }

(here, command substitution removes all trailing newline characters and in some shells including bash, also all the NUL ones).

Or to remove only one trailing newline like xclip -r does:

clipboard() { cat -- "$@" | perl -pe 's/\n$// if eof' | xclip -sel c; }

And use as:

cmd | clipboard
clipboard <<< "$var"
clipboard some-file and-some-other

In any case, using echo, or unquoted command substitutions as in your echo -n $(CMD_TO_COPY) approach is not correct.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.