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 2024Next, we'll define the DATE variable and assign the "date" string to it:
user@host:~$ DATE=dateWe can reference a variable by prefixing it with $. Let's verify the variable definition using the echo command:
user@host:~$ echo $DATE
dateNow, 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'
$DATEThe $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"
dateSince "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 2024This might be confusing, but here's what happens:
$DATEis referenced, resulting in "date"- The "date" command is then executed within the backquotes
- The output of the
datecommand 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.