Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the exclamation mark to be treated as a literal in double quotes in bash? [duplicate]

Tags:

bash

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?

like image 987
Melab Avatar asked Oct 19 '25 17:10

Melab


1 Answers

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!
like image 164
John1024 Avatar answered Oct 22 '25 06:10

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!