2.12. Hard and Soft Quotes

Double quotes are known as soft quotes, since shell variable references, history events (!), and command output capture ($() or ``) are all expanded when used inside double quotes.

shell-prompt: history
  1003  18:11   ps
  1004  18:11   history

shell-prompt: echo "!hi"
echo "history"
history

shell-prompt: echo "Today is `date`"
Today is Tue Jun 12 18:12:33 CDT 2018

shell-prompt: echo "$TERM"
xterm
        

Single quotes are known as hard quotes, since every character inside single quotes is taken literally as part of the string, except for history events. Nothing else inside hard quotes is processed by the shell. If you need a literal ! in a string, it must be escaped.

shell-prompt: history
  1003  18:11   ps
  1004  18:11   history
shell-prompt: echo '!hi'
echo 'history'
history
shell-prompt: echo '\!hi'
!hi
shell-prompt: echo 'Today is `date`'
Today is `date`
shell-prompt: echo '$TERM'
$TERM
        

What will each of the following print? ( If you're not sure, try it! )

#!/usr/bin/env bash

name='Joe Sixpack'
printf "Hi, my name is $name.\n"
        
#!/usr/bin/env bash

name='Joe Sixpack'
printf 'Hi, my name is $name.\n'
        
#!/usr/bin/env bash

first_name='Joe'
last_name='Sixpack'
name='$first_name $last_name'
printf "Hi, my name is $name.\n"
        

If you need to include a quote character as part of a string, you have two choices:

  1. "Escape" it (precede it with a backslash character):

    printf 'Hi, I\'m Joe Sixpack.\n'
                
  2. Use the other kind of quotes to enclose the string. A string terminated by double quotes can contain a single quote and vice-versa:

    printf "Hi, I'm Joe Sixpack.\n"
    printf 'You can use a " in here.\n'
                

No special operators are needed to concatenate strings in a shell script. We can simply place multiple strings in any form (variable references, literal text, etc.) next to each other.

printf 'Hello ,'$var'.'     # Variable between two hard-quotes strings
printf "Hello, $var."       # Variable between text in a soft-quoted string
        

2.12.1. Self-test

  1. What is the difference between soft and hard quotes?
  2. Show the output of the following script:
    #!/bin/sh
    
    name="Bill Murray"
    printf "$name\n"
    printf '$name\n'
    printf $name\n