DEV Community

Tiberius Mairura
Tiberius Mairura

Posted on

Differences between Single and Double Quotes in Bash

Although for the most part they behave almost exactly the same, single quotes ('') and double quotes ("") are fundamentally different in Bash.

How different are they?

Well, assume we have the a script hello-world.sh which takes in one positional argument and prints a message to the terminal:

#!/bin/bash
echo "Hello, $1" # using double quotes
Enter fullscreen mode Exit fullscreen mode

Execute

hello-world.sh Tiberius
Enter fullscreen mode Exit fullscreen mode

Output

# => Hello, Tiberius
Enter fullscreen mode Exit fullscreen mode

That executes and gives us the expected output. Great!

Now let us have a look at what happens when we instead use single quotes with the same script:

#!/bin/bash
echo 'Hello, $1' #using single quotes
Enter fullscreen mode Exit fullscreen mode

Execute

hello-world.sh Tiberius
Enter fullscreen mode Exit fullscreen mode

Output

# => Hello, $1
Enter fullscreen mode Exit fullscreen mode

Well, from the second output above, we see that the result is not what we expected.

What happened?

When using double quotes, bash will protect all the characters enclosed in the double quotes. That is to say, bash will read them all without giving them any special treatment or meaning. However, when it encounters $ it will expand the $ and replace it with the meaning it carries. In our example, this evaluates to the name passed to bash when executing the script.

On the other hand, the single quotes protect everything enclosed including the $. Therefore, when executing the script, bash does not expand the $ to give it the meaning it carries. Rather, it simply prints it out in its literal form. That is why the argument for second script did not evaluate to the value passed.

What if I want to use the $ symbol?

If at all we wish to use the $ symbol, we will have to instruct bash to escape it where appropriate.

Here is an example:

#!/bin/bash
echo "Hello, $1! Today you earned \$2." #using $ as a symbol
Enter fullscreen mode Exit fullscreen mode

Execute

hello-world.sh Tiberius
Enter fullscreen mode Exit fullscreen mode

Output

# => Hello, Tiberius! Today you earned $2.
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • In bash, single quotes and double quotes behave almost the same but they have different behaviors in certain cases.
  • If you want to evaluate the value of a variable in a string, use a double quotes.
  • Double quotes allow bash to expand the variable name and replace it with the actual value.
  • Using single quotes will not allow bash to evaluate the value of a variable in a string. Rather than, it prints the variable name.

Top comments (0)