2

I got this strange error message trying to write shebang to a python script:

$ echo "#!/usr/bin/env python" > scripts/sandbox.py 
-bash: !/usr/bin/env: event not found

$ echo "say what?" > scripts/sandbox.py

Immediately doing the same thing but without using shebang line works. What is this behavior and how can it be overcome?

halfer
  • 19,824
  • 17
  • 99
  • 186
codyc4321
  • 9,014
  • 22
  • 92
  • 165

1 Answers1

11

! is a special character to bash, it is used to refer to previous commands. It is expanded within double-quotes. To avoid that, enclose them in single-quotes instead:

echo '#!/usr/bin/env python' > scripts/sandbox.py 

@mklement0 clarified it beautifully in a comment:

More specifically, ! is special to Bash's history expansion feature, which is on by default (only) in interactive shells. In addition to avoiding it by using single-quoted strings, it can be turned off altogether with set +H

Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236
  • 2
    More specifically, `!` is special to Bash's _history expansion_ feature, which is on by default (only) in interactive shells. In addition to avoiding it by using single-quoted strings, it can be turned off altogether with `set +H`. – mklement0 Mar 15 '17 at 00:21