Prevent accidental execution of commands in Linux if pasting text containing one or more return characters
Solution 1:
What you want is called 'bracketed paste', a feature that's available in some shells.
If your version of bash supports it, you can turn it on for the current session like so:
bind 'set enable-bracketed-paste on'
Now try it out by pasting multiple lines:
echo Hello world
echo Again, I say, hello!
The shell recognises that the text was pasted (not typed), and waits with a prompt for your confirmation. If it all looks safe to proceed, hit the Enter key. If not, hit Control-C to cancel.
If you'd like to enable bracketed paste for every new session, add the command to your .inputrc file:
cd ~
echo "set enable-bracketed-paste" >> .inputrc
Another option is to switch from bash to zsh, where bracketed paste is enabled by default. To replace your current shell with a zsh shell:
exec zsh
With zsh, pasted text gets highlighted, which is nice. Again, hit Enter to execute the command/s or Control-C to cancel.
If you like zsh, and wish to make it the default shell:
chsh -s /bin/zsh
Solution 2:
If you're using PuTTY on Windows, here's an AutoHotKey script which will detect if you're trying to paste something into PuTTY that has one or more newlines and if so will confirm you're wanting to do so.
Tip: you can hit the space bar or keypad enter key as an easy way to press "Yes".
Note: this script uses ctrl+v to paste into PuTTY, but you could replace ^v
with RButton
if you wanted to hook this into the right-click-to-paste default functionality of PuTTY.
#ifwinactive ahk_class PuTTY
^v::
var := clipboard
var := RegExReplace(var, "\r\n?|\n\r?", "`n", lineNum)
If(lineNum>0)
{
MsgBox, 4, , There are one or more newlines in what you're pasting, are you sure you want to continue?
IfMsgBox Yes
SendInput {Shift down}{Insert}{Shift Up}
else IfMsgBox No
return
}
else
{
SendInput {Shift down}{Insert}{Shift Up}
}
return
#ifwinactive
Solution 3:
Use Ctrl
+X
Ctrl
+E
(“edit current line”) before pasting. This will start your default editor; you have to save and quit, then the pasted commands are executed.