zhuguowei zhuguowei - 1 year ago 69
Bash Question

different result when echo some string using single/double quotes

echo some string when use single quotes it's printed successfully

➜ ~ echo 'LOGIN_IDENTITY=sdf!121sdf$78sd!8'

but when use double quotes, it cannot be printed successfully and changed to another strange commands

➜ ~ echo "LOGIN_IDENTITY=sdf!121sdf$78sd!8"
➜ ~ echo "LOGIN_IDENTITY=sdffind . -name 'application.properties' | xargs grep 'login'sdf$78sdawk '{print "\""$0"\""}' a"

So what's wrong with double quotes?

Answer Source

It is because of Parameter Expansion in shell, when you have an ! character within the double-quotes, it tried to expand it to have a value.

Following excerpt from man bash page, history-expansion subsection:

History expansions are introduced by the appearance of the history expansion character, which is ‘!’ by default. Only ‘\’ and ‘'’ may be used to escape the > history expansion character, but the history expansion character is also treated as quoted if it immediately precedes the closing double quote in a double-quoted string.

You can avoid the expansion either by using single-quotes(')

$ echo "LOGIN_IDENTITY=sdf!121sdf$78sd!8"
-bash: !121: event not found

change the above assignment to

$ echo "LOGIN_IDENTITY=sdf"'!'"121sdf$78sd"'!'"8"

Notice the single-quote around the ! character.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download