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! )

#!/bin/sh -e

name='Joe Sixpack'
printf "Hi, my name is $name.\n"
        
#!/bin/sh -e

name='Joe Sixpack'
printf 'Hi, my name is $name.\n'
        
#!/bin/sh -e

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 'I'm a Unix scripting "newbie".\n'
                

No operator is needed to concatenate strings in a shell command. We can simply place multiple strings in any form (variable references, literal text, etc.) next to each other.

var=Joe
printf 'Hello, ''Joe.'
printf "Hello, "'Joe.'
printf 'Hello ,'$var'.'     # Variable reference between hard-quoted strings
printf "Hello, $var."       # Variable between text in a soft-quoted string
        
Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What shell constructs are expanded when found inside hard quotes?

  2. What shell constructs are expanded when found inside soft quotes?

  3. What is the output of the following script if it is run in /home/joe?

    #!/bin/sh -e
    
    cwd=$(pwd)
    printf "The CWD is $cwd.\n"
    string='The CWD is $cwd.\n'
    printf "$string"
            
  4. How do we print a single quote character in a shell command?

  5. How do we concatenate two strings in a shell command?