Echo "#!" fail - "event not found"

The following fails, and I do not understand why:

$ echo "#!" 

The following error message is also with the same error message:

 $ echo "\#!" 

error message:

 -bash: !": event not found 

Why is this failing? How to do echo instead?

+10
source share
5 answers

! The character is used to expand the history of csh style.

If you do not use this function, set +o histexpand (also set +o histexpand as set +H ) disables this behavior. It is disabled for scripting, but often included for interactive use. In such cases, my personal recommendation is to permanently disable it by adding set +o histexpand to your .bash_profile (or .bashrc if you don't have .bash_profile ; it's more complicated than I want to try to fit in in brackets).

As a workaround, you can use single quotes instead of double quotes, bearing in mind, of course, their different semantics. For example, if you need to combine quotation marks with variable interpolation, you can change

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

in

  echo '#!'"$SHELL" 

(note the adjacent lines in single and double quotes; after the shell finishes working with it, the quotes will be removed and the line #! will be displayed next to the value of the SHELL variable without spaces between them) or a number of other common workarounds, such as

  printf '#!%s\n' "$SHELL" 
+14
source

By default, bash supports a csh compatible history extension.

In bash

 echo #! 

will only print a new line, as # starts a comment.

IN

 echo "#!" 

# is part of a line starting with " . Such lines are still checked by bash for special characters. ! is a special character if it is followed by any other text.

 -bash: !": event not found 

In this case, bash expects the token !" Refers to the previous command in the shell history, starting with " , and does not find it. By itself ! does not cause this behavior:

 $ echo \# ! # ! $ echo fee ! fie fee ! fie 

Finally,

 $ echo !echo 

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

 echo echo '# !' 

and the second line is the result of the extended command: echo #!


See also: Bash History Extension Page

+9
source
 echo '#!' 

Basically, with double quotes ( " ), aka" weak quotation ", Bash does some strange things with a string, such as replacing variables. With a single ( ' ) aka" strong quoting, a string is taken literally.

See here for a more detailed explanation of citation.

+4
source

Another workaround might be to add extra space after the "!"

 # echo "#! " #! 
+4
source

In my case, all the commands work. Perhaps you can specify your environment.

 $ echo "\#\!" \#\! $ echo "#!" echo "#" # $ echo "#!" echo "#" # $ echo $BASH_VERSION 3.2.48(1)-release 
+2
source

All Articles