To turn off history expansion, use:
set +H
Documentation
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 +H
option to the set
builtin command (see SHELL BUILTIN COMMANDS
below). Non-interactive shells do not perform history expansion by default. [Emphasis added.]
Escaping !
when history expansion is on
If 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
.
How can I properly escape ! in double quotes?
To eliminate the extra backslash seen here:
$ echo -e "Testing\!"
Testing\!
Use single quotes:
$ echo -e "Testing"'!'
Testing!