Bash Scripting - Quotes

In this post, we will discuss quotes, which are a simple but important aspect of bash scripting. In bash, we have two types of quotes: single quotes and double-quotes.

Let's start with a simple example to see how they differ:

[root@scriptbox scripts]# var_1="Devops"
[root@scriptbox scripts]# echo $var_1
[root@scriptbox scripts]# var_1='Devops'
[root@scriptbox scripts]# echo $var_1

As you can see, there is no difference when a variable contains a single word. This is because storing a single word in a variable works fine until we need to store a few words or special characters like % $#@, etc., at which point our variable assignment will fail. Let's see how it works:

[root@scriptbox scripts]# echo "Variable value will work: $var_1"
Variable value will work: Devops
[root@scriptbox scripts]# echo 'Variable value will NOT work: $var_1'
Variable value will NOT work: $var_1

As you can see, when using double quotes, the variable worked as expected but in a single quote, it print the variable name instead of its value. As a result of this example, we can conclude that a single quote removes the meaning of special characters ($ is a special character:)).

So, what happens when we need to print the $ symbol while using double quotes? In that case, we will use '\' which removes the meaning of the next character:

[root@scriptbox scripts]# echo "Print $var_1 and $5"
Print Devops and
[root@scriptbox scripts]# echo 'Print $var_1 and $5'
Print $var_1 and $5
[root@scriptbox scripts]# echo "Print $var_1 and \$5"
Print Devops and $5

1 view0 comments