Clipboard – Remove Trailing New Line to Prevent Terminal Execution

clipboardnewlines

Is there some way to run whatever you copy to the 'clipboard' through some sort of filter? Ideally to strip out the trailing newline from something you copy, so that it doesn't auto-run in the terminal?

This is what it looks like when I copy the test in question, and I sometimes forget this is a new line.
enter image description here

Best Answer

Good modern terminals support bracketed paste: when you use the terminal's paste command, it sends special escape sequences around the clipboard content. If your shell supports bracketed paste, it'll paste the clipboard content including any control characters as-is, and in particular a trailing newline will not trigger the execution of the command.

Zsh ≥5.1 supports bracketed paste and has it on by default. Older versions can be taught. Bash ≥4.4 supports bracketed paste if you add set enable-bracketed-paste on to ~/.inputrc.

If your terminal or shell doesn't support bracketed paste, you could define a shell function that pastes without the trailing newline.

In zsh, the following command recalls the content of the clipboard, minus trailing newlines, and brings it up for editing (even if there are multiple lines):

print -z -- "`xsel -b`"

In bash, you can push the content of the clipboard minus trailing newlines to the history stack. After this, press Up to bring up the command for editing.

history -s -- "`xsel -b`"
Related Question