Browse topics

Quoting and word splitting

Version
5.3
Review
Draft

Summary#

In command arguments, use double quotes around a variable expansion to keep its value together, even when it contains spaces or is empty. Use single quotes for literal text. An unquoted expansion can split into fields using IFS. Bash can then expand wildcard characters in those fields to matching filenames.

Syntax#

bash
printf '%s\n' 'literal $label and *.txt'
printf '%s\n' "$label"
some_command "$@"

Use "$@" to forward the current positional arguments individually, including empty arguments. "$*" joins them with the first character of IFS, with a space if IFS is unset, or with no separator if IFS is empty.

Example#

The same two values form different arguments when passed to set --. Unsetting IFS inside the subshell selects the default splitting on spaces, tabs, and newlines.

bash
(
  unset IFS
  label='night shift'
  empty=

  set -- "$label" "$empty"
  printf 'quoted (%d):\n' "$#"
  printf '<%s>\n' "$@"

  set -- $label $empty
  printf 'unquoted (%d):\n' "$#"
  printf '<%s>\n' "$@"
)

Expected output#

Text
quoted (2):
<night shift>
<>
unquoted (2):
<night>
<shift>

Common mistakes#

Quote a filename variable at the point where you pass it to a command. A value containing * can otherwise expand to names in the current directory. Quotes stored inside a variable are ordinary characters. Build an indexed array when you need to assemble a list of arguments.

Version applicability#

The quoting, word splitting, and positional argument forms shown here work on Bash 3.2. The complete example uses only Bash builtins.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0