Echo Bang – How to Echo a Bang!

bashcommand lineecho

I tried to create a script by echo'ing the contents into a file, instead of opening it with a editor

echo -e "#!/bin/bash \n /usr/bin/command args"  > .scripts/command

The output:

bash: !/bin/bash: event not found

I've isolated this strange behavior to the bang.

$ echo !
!  

$ echo "!"
bash: !: event not found

$ echo \#!
#!

$ echo \#!/bin/bash
bash: !/bin/bash: event not found
  • Why is bang causing this?
  • What are these "events" that bash refers to?
  • How do I get past this problem and print "#!/bin/bash" to the screen or my file?

Best Answer

Try using single quotes.

echo -e '#!/bin/bash \n /usr/bin/command args'  > .scripts/command

echo '#!'

echo '#!/bin/bash'

The problem is occurring because bash is searching its history for !/bin/bash. Using single quotes escapes this behaviour.

Related Question