What causes a copy/paste in terminal to sometimes execute the command

clipboardcommandterminal

When you paste some command in terminal, it will sometimes automatically execute the command (just like if the "Enter" key was pressed), sometimes not.

I've been using Linux for ages, pasted thousands of commands in various consoles on many distros, and I am still unable to tell if the command I'm about to paste will be executed automatically or not.

What triggers this behavior?

Best Answer

It's the return character in the text you are copying that's triggering the automatic execution.

Let's take a different example, copy these lines all at once and paste them into your terminal:

echo "Hello";
echo "World";

If you look in your terminal, you will not see this:

$ echo "Hello";
echo "World";

You will see this (there may also be a line saying World):

$ echo "Hello";
Hello
$ echo "World";

Instead of waiting for all the input to be pasted in, the first line executes (and for the same reason, the second line may or may not do so as well). This is because there is a RETURN character between the two lines.

When you press the ENTER key on your keyboard, all you are doing is sending the character with the ASCII value of 13. That character is detected immediately by your terminal, and knows it has special instructions to execute what you have typed so far.

When stored on your computer or printed on your screen, the RETURN character is just like any other letter of the alphabet, number, or symbol. This character can be deleted with backspace, or copied to the clipboard just like any other regular character.

The only difference is, when your browser sees the character, it knows that instead of printing a visible character, it should treat it differently, and has special instructions to move the next set of text down to the next line. The RETURN character and the SPACE character (ascii 32), along with a few other seldom used characters, are known as "non-printing characters" for this reason.

Sometimes when you copy text from a website, it's difficult to copy only the text and not the return at the end (and is often made more difficult by the styling on the page).


Experiment time!

Below you will find two commands that will illustrate the problem, and that you can "practice" on. Start your cursor right before echo and drag until the highlight is right before the arrow:

echo "Wait for my signal...";<- End cursor here right after the semicolon

And now try the second command. Start your cursor right before echo and drag down until the cursor is on the second line, but is right in front of the <- arrow. Copy it, and then paste it into your terminal:

echo 'Go go go!';
<- End cursor here right before the arrow

Depending on your browser, it may not even be visible that the text you selected went over two lines. But when you paste it into the terminal, you will find that it executes the line, because it found a RETURN character in the copied text.