In this post we will learn, how to print variable value inside single and double quotes. Today I was working on some bash scripting and got this requirement. The script is working wonderfully and as expecting output was also coming. Today we will share this basic bash scripting.
Explaining step by step , which gives you more understanding
Variable = foo
Value = bar
Define Variable and its value
In below example, we have defined the variable foo with value bar
[root@localhost ~]# foo=bar [root@localhost ~]#
Print Variable’s value
Print variable’s value by using $ inside double quotes.
[root@localhost ~]# echo "$foo" bar [root@localhost ~]#
Or using $ sign only to print Variable’s value
[root@localhost ~]# echo $foo bar [root@localhost ~]#
What happen when we try to call variable by using single quotes. See the below example.
In this example, you can see that by using single quotes it is printing $ sign with variable name. Means not calling the variables value even by using $ sign.
[root@localhost ~]# echo '$foo' $foo [root@localhost ~]#
In above lesson we learn that when we use $ sign with variable inside double quotes, it will print the variable’s value.
Print Variable’s value inside single quotes
In this example, inside double quotes we have written variable with $ sign again inside the single quotes.
Then it prints the variable’s value inside single quotes.
[root@localhost ~]# echo "'$foo'" 'bar' [root@localhost ~]#
Print Variable’s value inside double quotes
Now our requirement is to print variable’s value inside double quotes.
See the below given example
[root@localhost ~]# echo ""$foo"" "bar" [root@localhost ~]#