Home echo "#!" fails -- "event not found"
Reply: 5

echo "#!" fails -- "event not found"

erikbwork Published in 2012-08-05 11:45:44Z

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?

tripleee Reply to 2017-11-10 04:42:25Z

The ! character is used for csh-style history expansion.

If you do not use this feature, set +o histexpand (aka set +H) turns off this behavior. It is turned off for scripts, but often enabled for interactive use.

As a workaround, you can use single quotes instead of double quotes -- keeping in mind, of coure, their different semantics. If you need to combine quoting with variable interpolation, for example, you can change

echo "#!$SHELL"  # oops, history expansion breaks this


 echo '#!'"$SHELL"

(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 variable SHELL with no space between them) or a number of other common workarounds like

 printf '#!%s\n' "$SHELL"
Henk Langeveld
Henk Langeveld Reply to 2012-08-05 15:00:20Z

By default, bash supports csh compatible history-expansion.

In bash

echo #!

will only print a newline, as # starts a comment.


echo "#!"

the # is part of the string started with ". Such strings are still inspected by bash for special characters. ! is a special character iff it is followed by any other text.

-bash: !": event not found

In this case, bash expects the !" token to refer to a previous command in shell history starting with ", and does not find one. All by itself, ! will not trigger this behaviour:

$ echo \# !
# !

$ echo fee ! fie
fee ! fie


$ echo !echo

produces two lines, the first line is printed by the shell to show how the pattern above expands to:

echo echo '# !'

while the second line is just the result of executing the expanded command: echo # !

See Also: The Bash man page on History Expansion

Staven Reply to 2012-08-05 11:50:08Z
echo '#!'

Basically, with double quotes (") aka "weak quoting", Bash does some wacky things with the string, like variable substitution. With single (') aka "strong quoting" the string is taken literally.

See e.g. here for a more in-depth explanation of quoting.

devanand Reply to 2012-08-05 11:50:19Z

In my case all commands are working. Maybe you can specify your environment.

$ echo "\#\!"
$ echo "#!"
echo "#"
$ echo "#!"
echo "#"
JG_ Reply to 2016-06-10 06:27:08Z

Another workaround may be to put an extra space after the "!" :

# echo "#! "
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.422736 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO