2

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 if I type the following commands:

$ 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?

Arjan
  • 31,511
bodacydo
  • 390

1 Answers1

0

Your code will be easier to read if you do it like this:

:~$ name='boda'
:~$ var="hello! my name is $name! bye!" && echo $var
hello! my name is boda! bye!
  • && - The 2nd command echo $var is executed only if the 1st command var="hello! my name is $name! bye!" succeeds.

  • :~$ - It is not typed in this example because it denotes the bash prompt.

  • ! - You don't need to escape the ! in the above command because it is inside a pair of double quote characters.

karel
  • 13,706