The following fails and I don’t understand why:
$ echo "#!"
the following also fails with the same error message:
$ echo "\#!"
the error message:
-bash: !": event not found
Why does it fail? How should the echo be done instead?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
!character is used forcsh-style history expansion.If you do not use this feature,
set +o histexpand(akaset +H) turns off this behavior. It is turned off for scripts, but often enabled for interactive use. In such cases, my personal recommendation is to turn it off permanently by addingset +o histexpandto your.bash_profile(or.bashrcif you don’t have a.bash_profile; this is more complex than I want to try to fit into a parenthetical).As a workaround, if for some reason you cannot or don’t want to turn off and forget about this legacy
cshfeature, you can use single quotes instead of double quotes — keeping in mind, of course, their different semantics. If you need to combine quoting with variable interpolation, for example, you can changeinto
(notice the adjacent single-quoted and double-quoted strings; after the shell is done with this, the quotes will be removed and the string
#!will be output next to the value of the variableSHELLwith no space between them) or a number of other common workarounds like… though as remarked in a comment, even single quotes don’t necessarily prevent this from happening when they are at the end of a pipeline.