Bash – Why quotes are retained in string variables when surrounded by single quotes

bashquotingstring

I needed to retain the double quotes around a string variable defined in bash in order to be able to pass it to a dialect of the Scheme programming language. My question is why are the double quotes retained when placed inside another set of single quotes? In order to illustrate this I give some examples from my bash command prompt:

$ str1=hey
$ echo $str1
hey
$ str2="hey"
$ echo $str2
hey
$ str3='hey'
$ echo $str3
hey
$ str4='"hey"'
$ echo $str4
"hey"
$ str5="'hey'"
$ echo $str5
'hey'
$ 

Best Answer

A single-quoted string will retain the string as a literal. A double-quoted string will retain the string with variable interpolation and expansion. This is explained in the bash man page - see the section titled QUOTING

There are three quoting mechanisms: the escape character, single quotes, and double quotes.

A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of {newline}. If a \{newline} pair appears, and the backslash is not itself quoted, the \{newline} is treated as a line continuation (that is, it is removed from the input stream and effectively ignored).

Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or {newline}. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

Related Question