Terminal · foundation

Quoting and escaping

Shell quoting controls which characters retain literal meaning during parsing and expansion: single quotes preserve all enclosed characters, double quotes preserve most text while allowing selected expansions, and backslash quotes one following character in context.

Why it matters

Correct quoting preserves argument boundaries, prevents unintended globbing or word splitting, and is essential when values contain whitespace or shell metacharacters.

Mental model

How to reason about quoting and escaping

Quoting changes the shell's interpretation before a program receives arguments; it is not decoration added to the text delivered to the program.

Analogy

Quotation works like protective packaging applied before shipping: it keeps intended pieces together while selected openings in double quotes still allow controlled substitutions.

Examples

See the boundary, not just the happy path

Worked example · Preserve one argument

mkdir -- "Quarterly Reports"

Double quotes keep the space inside a single argument, so mkdir receives one directory name rather than two words.

Worked example · Expand a value safely

printf '%s\n' "$HOME"

Double quotes allow parameter expansion while keeping the expanded path as one argument and suppressing pathname expansion.

Useful contrast · Literal variable notation

printf '%s\n' '$HOME'

Single quotes prevent parameter expansion, so printf receives the five literal characters $HOME.

Common mistakes

Misconceptions to remove early

Quoting a variable at assignment but not at use

The critical context is expansion; in shells where unquoted expansion splits or globs, later use as $value can still change argument boundaries.

Trying to escape a single quote inside single quotes

In POSIX-like shell syntax, backslash has no special role inside single quotes; close the quote, add an escaped quote, then reopen it.

Quick check

Can you predict the result?

1. Which form expands HOME while preserving the result as one shell word?
  • "$HOME"
  • '$HOME'
  • $HOME/*
Answer: "$HOME"
2. Does a program normally receive the quote characters used to group a shell argument?
Answer: No; the shell consumes syntactic quotes while forming the program's arguments.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster