In Linux, single quotes ('
), double quotes ("
), and backquotes (`
) serve different purposes. The easiest way to understand their differences is by using the DATE variable, the "date" string, and the date
command.
Important:
'
... Single quotes- Everything within single quotes is interpreted as a string (ignoring any variables).
"
... Double quotes- Contents within double quotes are generally interpreted as strings. However, if a variable is included, it's referenced.
`
... Backquotes- Contents within backquotes are interpreted as commands.
First, let's look at the date
command, which prints the current date and time:
user@host:~$ date
Wed Sep 4 07:30:38 IST 2024
Next, we'll define the DATE variable and assign the "date" string to it:
user@host:~$ DATE=date
We can reference a variable by prefixing it with $
. Let's verify the variable definition using the echo
command:
user@host:~$ echo $DATE
date
Now, let's examine the output differences based on the quotation marks used.
Everything within single quotes is interpreted as a string:
user@host:~$ echo '$DATE'
$DATE
The $DATE
is treated as a literal string, not a variable reference.
Within double quotes, contents are generally interpreted as strings, but variables are referenced:
user@host:~$ echo "$DATE"
date
Since "date" was assigned to the DATE variable, the output is "date".
Contents within backquotes are interpreted as commands:
user@host:~$ echo `$DATE`
Wed Sep 4 07:31:18 IST 2024
This might be confusing, but here's what happens:
$DATE
is referenced, resulting in "date"- The "date" command is then executed within the backquotes
- The output of the
date
command is then echoed
To deepen your understanding, let's try combining techniques:
user@host:~$ echo "Today's date is `date`"
Today's date is Wed Sep 4 07:32:06 IST 2024
user@host:~$ echo 'Today's date is `date`'
Today's date is `date`
Notice the difference? In the second example with single quotes, everything is interpreted as a string, so the date
command isn't executed.