1

I want to put a string (comprising of specially ! sign) in a variable, say,

var="!f then"

Then I want to display the string or use it elsewhere:

echo $var

But when I enter with var="!f then" it gives the following:

var="for f in Tor*; do mv "$f" "$f-Win"; done then"

If I use escape like var="\!f then", then the escape character also comes in the string.

$ echo $var  
\\!f then

How can I use ! as an element in a string?

dessert
  • 39,982
  • 1
    If you aren't actively using history expansion, your life will be much easier if you turn it off. At the command line, run set +H. To keep it off, put set +H in your ~/.bashrc. – John1024 Dec 28 '17 at 05:41

2 Answers2

1

That's bash History Expansion you're experiencing:

!string
  Refer to the most recent command preceding the current position
  in the history list starting with string.

As I explain here, history expansion is performed inside double quotes, so two ways to quote remain for !:

var=\!f\ then # either use <b>only</b> backslash
var='!f then' # or just single quotes
dessert
  • 39,982
0

The ! character is a special character that bash uses to introduce a history command (see man bash), and is used like !! to re-execute the next command. Use \! instead.

dessert
  • 39,982
waltinator
  • 36,399