Double Quotes
Let's say we want we assign a string with spaces to a variable. If we try:
var=This is a test
We get an error:
$ var1=This is a test.
-bash: is: command not found
The Shell assigns "This" to the variable and thinks the next word is a command.
To accomplish this we can surround the text with quotes.
ajay.mittal@AMITTAL-NB03 ~/temp
$ var1="This is a test."
ajay.mittal@AMITTAL-NB03 ~/temp
$ echo $var1
This is a test.
Double quotes will not ignore dollar signs , back quotes or backslashes.
ajay.mittal@AMITTAL-NB03 ~/temp
$ var2="This is var1:$var1"
ajay.mittal@AMITTAL-NB03 ~/temp
$ echo $var2
This is var1:This is a test.
Using the back quote:
ajay.mittal@AMITTAL-NB03 ~/temp
$ var1=" `date` is todays date"
ajay.mittal@AMITTAL-NB03 ~/temp
$ echo $var1
Sun, Oct 28, 2018 6:15:10 PM is todays date
The backquote indicates execution of a command and is interpreted by the shell.
Single Quotes
Single quotes are more restrictive. They treat the string as it is without any interpretation.
[amittal@hills sed]$ var1="Some value"
[amittal@hills sed]$ echo '$var1'
$var1
The value of the variable "var1" is not printed out.
Backslash
We can use the backslash to assign and remove special meaning to characters .
[amittal@hills sed]$ echo "a a" | grep "\s"
a a
[amittal@hills sed]$ echo "aa" | grep "\s"
The above states that "grep" should look for the "space" character .
[amittal@hills sed]$ echo "aa^" | grep "\^"
aa^
The above looks for the carat character . With the backslash we are actually looking at the character caret instead of looking for the pattern at the beginning of the string.
Command Substitution
[amittal@hills ~]$ var1=`date`
[amittal@hills ~]$ echo $var1
Tue Oct 30 17:42:18 PDT 2018
Using the back quote character we can execute the command inside and the use the output. In the above the "date" command is executed and the output is placed in the variable "var1" . We can confirm that by echoing the contents of the variable "var1" .