Why is Terminal automatically executing my command after pasting text?

Don't copy multiple lines of text, to paste. I can almost guarantee you're simply copying the last part of the line. If you're triple clicking to copy that line of code you're pasting, you're getting the newline at the end of the line. If you want to be sure, that is really the problem, then copy the entire line, except for the last letter/digit, and see if pasting that also includes a newline.


The text you're pasting includes a trailing newline. When you paste a newline, the shell running in the terminal sees that as pressing Enter, so it executes the command.

The paste operation is performed by the terminal emulator; it passes the pasted text to the application running in the terminal, in the same way that it passes the text typed by the user. See How do keyboard input and text output work? for more information about how input works. The application (here, the shell) has no way to distinguish between keystrokes and a paste operation.

Many terminal emulators these days support bracketed paste. In bracketed paste mode, the application can distinguish a paste operation from keystrokes. Bracketed paste is only useful if the application does something different with pasted text, so it's enabled by supporting applications, it isn't something that's configured by the user of the terminal emulator.

Zsh 5.1 (which came out a few weeks ago, so isn't available yet in most distributions) adds support for bracketed paste mode. When you paste text, it's just inserted on the command line, and you can edit it before pressing Enter to execute the command line.

Users of oh-my-zsh can use the safe-paste plugin even in earlier versions of zsh.

Another thing you can do in zsh is to make it insert the selection as a string, with quoting (in the form of backslashes before every shell special character such as whitespace). Type `xsel` to get the primary selection (automatic mouse selection), or `xsel -b` to get the clipboard content (text copied with Ctrl+C), then press Tab.

If you have an older zsh version and you want to insert the clipboard content without quoting, you can define a function that inserts the selection.

function zle_insert_x_selection {
  LBUFFER+=$(xsel ${NUMERIC+-b} -o </dev/null)
}
zle -N zle_insert_x_selection
bindkey '\e\C-v' zle_insert_x_selection

With this in your .zshrc, you can press Ctrl+Alt+V to insert the primary selection, or Ctrl+U Ctrl+Alt+V to insert the clipboard content. They are inserted before the cursor, unchanged except with no trailing newline. See Share the clipboard between bash and X11 for something similar in bash.


If you're using bash as your shell, you can press Ctrl-X Ctrl-E to bring up an editor (defined by $VISUAL or $EDITOR, e.g. vi or perhaps nano).

You can then paste your commands into that exactly as you would if you were editing a file. They will be executed if you save and exit. Or cancelled if you quit without saving.