The exclamation mark has a special function that I don't care to understand and its significance is a positive pain in my rear whenever I need to use echo (or any other command involving strings) in the dynamic creation of scripts. Putting ! in single quotes
# echo 'Testing!'
Testing!
works, but I have to use double quotes in bash for reasons of consistency. However, this has its problems:
# echo -e "Testing\!"
Testing\!
How can I properly escape ! in double quotes?
To turn off history expansion, use:
set +H
From man bash:
HISTORY EXPANSION
The shell supports a history expansion feature that is similar to the history expansion in csh. This section describes what syntax features are available. This feature is enabled by default for interactive shells, and can be disabled using the+Hoption to thesetbuiltin command (see SHELL BUILTIN COMMANDS below). Non-interactive shells do not perform history expansion by default. [Emphasis added.]
! when history expansion is onIf history expansion is enabled, ! will be an active character unless (1) it is escaped with a backslash, or (2) it is in single-quotes.
For example, to establish a history, let's enable history and run the ls command:
$ set -H
$ ls dummy
ls: cannot access dummy: No such file or directory
Now use !:
$ echo !ls
echo ls dummy
ls dummy
Thus, history expansion made a substitution. Let's try it double-quotes:
$ echo "!ls"
echo "ls dummy"
ls dummy
It is still active. If we need it to be disabled in double-quotes, it must be escaped with a backslash:
$ echo "\!ls"
\!ls
Or else we can put it in single-quotes:
$ echo '!ls'
!ls
However, I agree with Jonathan Leffler's comment: it is best to keep history expansion turned off. I have set +H in my ~/.bashrc.
To eliminate the extra backslash seen here:
$ echo -e "Testing\!"
Testing\!
Use single quotes:
$ echo -e "Testing"'!'
Testing!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With