Why sometimes when I paste a command on my bash prompt it gets executed even if I don't press Enter?

StackOverflow https://stackoverflow.com/questions/857029

  •  21-08-2019
  •  | 
  •  

Question

The command get executed without the need of pressing Enter. This can be dangerous sometimes...

Why is that and how can I prevent it?

Was it helpful?

Solution

Because you paste new line character with it. It's sometimes can be useful, for example, you can copy/paste many commands (long multi-line scripts) at once.

Well, It has never occurred to me to prevent this particular behavior. It's normal and expected. WYPIWYG - what you paste is what you get.

OTHER TIPS

You're pasting one or more newline characters. Other than simply not copy and pasting newline characters there are a few things you can do to work around this:

  • For single-line commands, type "#" first, so the command will be commented out. You can then go back up and edit it.

  • Use bash's (seemingly little-known) edit-and-execute-command feature. To invoke it you can hit CTRL-x CTRL-e if you use emacs keybindings (the default) or ESC v if you use vi keybindings. This will invoke a text editor containing your current command-line. You can then paste into the editor, and edit the command. Once you save and quit the command(s) saved by the editor will be executed (if you want to abort either comment out all lines or completely clear the buffer). You can set which editor is used with either the FCEDIT or EDITOR environment variables.

A quick way to prevent execution is to type the comment character #, then paste the command.

I often do that because I fat-finger when copying and grab extraneous characters.

When you paste after the comment character, then the command is in the history buffer and you can edit it, uncomment it, and run it.

--- reply to comment

You're right, this only works for single-line commands. If you have a multi-line one in the clipboard, you can pipe the clipboard data through sed.

Stupid bash trick # 4 million and one:

prompt:$ xclip -o -selection clipboard | sed --regexp-extended 's/^(.*)$/# \1;/'

will turn this:

for i in *.JPG;

do echo mv $i ${i/.JPG/.jpg};

done;

into this:

# for i in *.JPG;

# do echo mv $i ${i/.JPG/.jpg};

# done;

Which is really not worth the effort, but kinda fun ;>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top