echo “#!” fails — “event not found”

前端 未结 5 553
长情又很酷
长情又很酷 2020-11-22 08:30

The following fails and I don\'t understand why:

$ echo \"#!\"

the following also fails with the same error message:

$ echo         


        
5条回答
  •  隐瞒了意图╮
    2020-11-22 08:41

    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. In such cases, my personal recommendation is to turn it off permanently by adding set +o histexpand to your .bash_profile (or .bashrc if 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 csh feature, 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 change

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

    into

     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"
    

提交回复
热议问题