Back to tools

Quoting and escaping

With or without quotes, single or double: the same line can hand a command very different arguments. Type one here and watch the shell read it step by step.

What the command receives

After expansion, splitting and quote removal: what the command really gets. · is a space, → a tab.

  1. cmdprintf
  2. $1[%s]\n
  3. $2hello
  4. $3world
  5. $4hello···world

4 arguments

How the shell reads the line
printf '[%s]\n' $msg "$msg"
  • '…'in single quotes: as it is
  • ' " \quotes and escaping \: removed (grey)
  • $xexpanded (dotted underline)
  • '…'Single quotes: everything inside stays as it is; $, *, \ and spaces are not special. A single quote cannot appear inside
  • $msgUnquoted: replaced by 「hello world」, then split at blanks into 2 arguments (several blanks count as one), and any * in it matches file names
  • "…"Double quotes: spaces, * and | inside stay as they are, all one argument; but $variables, $(commands) and backquotes still expand, and \ works only before $ ` " \
  • "$msg"In double quotes: replaced by 「hello world」 and kept as one argument, spaces and all
Output
[hello]
[world]
[hello   world]

Exit status 0

The demo’s world

Runs in the simulator in /home/user/demo, with these variables and files.

Variables

  • HOME='/home/user'
  • name='Linux'
  • msg='hello world'
  • file='my notes.txt'
  • pattern='*.txt'
  • empty=''

Files in the current directory

  • a.txt
  • b.txt
  • my notes.txt
  • report.md
Good to know
  • Almost always put variables in double quotes: "$file". Unquoted, blanks in the value split it into several arguments, and * matches file names.
  • For text exactly as written, no expansion at all, use single quotes; to expand variables but keep blanks, use double quotes.
  • A single quote cannot go inside single quotes: write 'It'\''s', or use double quotes, "It's".
  • The quotes themselves are not passed to the command; they only tell the shell where arguments begin and end.
  • Wildcards, ~ and {a,b} expand only unquoted; when * matches nothing it is passed on as it is.
  • An unquoted empty variable vanishes; a quoted one is an empty argument. That is why [ $x = y ] fails when x is empty.
Explain

Examples

Basics
Variables
Expansions
Common traps