0

This question already has an answer here:

I can't figure out how to write ! symbol in bash scripts when putting it in double quotes strings.

For example:

var="hello! my name is $name! bye!"

Something crazy happens:

$ age=20
$ name='boda'
$ var="hello! my name is $name! bye!"

When I press enter at last command the command repeats itself (types itself) without the last !:

$ var="hello! my name is $name! bye"

If I press enter again

$ var="hello! my name is $name bye"

If i press enter again it disappears nothing gets output

$ 

If I try this:

$ echo "hello\! my name is $name\! bye\!"

Then it outputs: hello\! my name is boda\! bye\!

If i use single quotes then my name doesn't get expanded:

$ echo 'hello! my name is $name! bye!'

Outputs are: hello! my name is $name! bye!

I have it working this way:

$ echo "hello"'!'" my name is $name"'!'" bye"'!'

But it's one big mess with " and ' impossible to understand/edit/maintain/update.

Can anyone help?

marked as duplicate by Gilles bash Nov 29 '15 at 23:22

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

As you discovered, ! doesn't trigger history expansion inside single-quotes.

You could use printf with a format string containing the ! symbols in single quotes. For example:

$ name="boda"
$ printf 'hello! my name is %s! bye!\n' "$name"
hello! my name is boda! bye!

or

$ name="boda"
$ var=$(printf 'hello! my name is %s! bye!\n' "$name")
$ echo "$var"
hello! my name is boda! bye!
2

Disable history expansion; which is only enabled in interactive shells, via: set +H.

Not the answer you're looking for? Browse other questions tagged or ask your own question.