In shell, there is certain characters with special meanings, and escaping/quoting mechanisms to remove such special meanings as well. With the combination of special characters and escaping/quoting mechanisms, the final result is sometimes unclear. Here is my attempt to clear the confusion around the using of backslash (\) character in shell.

In shell/bash, we've got double quotes to suppress the special meaning of special characters (e.g. &, |, <, >) with the exception of $, `, \ and ! 1, and single quotes to suppress the special meaning of all special characters. Besides, we also have \ to selectively suppress special meaning of one following character.

Here is a table to showcase equivalent representaions of a string in three forms:

w/o quotes = double quotes = single quotes
\\ = "\\" = '\'
\\\\ = "\\\\" = '\\'
\n or n = "n" = 'n'
\\n = "\n" = '\n'
\a \b \c = "a" "b" "c" = 'a' 'b' 'c'
\\a \\b \\c = "\a" "\b" "\c" = '\a' '\b' '\c'
\$1 = "\$1" = '$1'
\`echo hi\` = "\`echo hi\`" = '`echo hi`'
\!git = (no equivalent) = '!git'
\\\!git = "\!git" = '\!git'

Tips:

  1. \ is simply striped when used without quotes, and eliminates the special meaning of the one character following it;

  2. \ is kept as is when used in double quotes, with the exception: "\$" => '$', "\`" => '`', "\\" => '\' and "\!" => '\!';

  3. \ is kept as is when used in single quotes, with no exceptions;

  4. If \ or single quotes ('') or double quotes ("") are used in $0, it calls the command/shell function/shell builtin, but won't call alias defined under that name.

Note: Sometimes it could be hard to determine how the shell actually parse your input if you are not very familiar with the internal parsing logic, so to see as the shell sees it, run set -x in your shell to debug your input.

References:

  • man bash, QUOTING section & HISTORY EXPANSION section

  1. ! is the default history expansion character, and has special meaning only when history expansion is enabled (enabled by default for interactive shells and disabled by default for scripts/non-interactive shells).