乐闻世界logo
搜索文章和话题

What is the difference between single quotes and double quotes in Shell scripts?

3月6日 21:33

The main differences between single quotes and double quotes in Shell scripts are as follows:

Single Quotes (' ')

  • Full quoting: All characters within single quotes are treated literally
  • No variable substitution: Variables within single quotes are not expanded
  • No command substitution: Backticks or $() within single quotes do not execute commands
  • No escape sequences: Escape characters (like \n, \t) within single quotes are not interpreted

Example:

bash
name='world' echo 'Hello $name' # Output: Hello $name echo 'Today is $(date)' # Output: Today is $(date) echo 'Line1\nLine2' # Output: Line1\nLine2

Double Quotes (" ")

  • Partial quoting: Special characters within double quotes are interpreted
  • Allows variable substitution: Variables within double quotes are expanded to their actual values
  • Allows command substitution: Backticks or $() within double quotes execute commands
  • Allows escape sequences: Escape characters within double quotes are interpreted

Example:

bash
name='world' echo "Hello $name" # Output: Hello world echo "Today is $(date)" # Output: Today is Fri Feb 28 12:38:28 CST 2026 echo "Line1\nLine2" # Output: Line1\nLine2 (requires -e parameter with echo)

Backticks ( ) and $()

  • Command substitution: Used to execute commands and return output
  • Recommend using $(): More readable and supports nesting

Example:

bash
files=`ls` # Traditional syntax files=$(ls) # Recommended syntax files=$(ls $(pwd)) # Supports nesting

Usage Recommendations

  1. Use double quotes when variable substitution is needed: echo "Hello $name"
  2. Use single quotes for literal output: echo '$HOME'
  3. Prefer $() for command substitution: result=$(command)
  4. String concatenation: echo "Hello" "$name" or echo "Hello $name"
标签:Shell