tl;dr: To quote a special character either escape it with a backslash \
or enclose it in double " "
or single quotes ' '
. Tab ↹ Completion takes care of proper quoting.
What you're asking for is called Quoting:
Quoting is used to remove the special meaning of certain characters or words to the shell. (…) There are three quoting mechanisms: the escape character, single quotes, and double quotes.
[citations taken from man bash
]
Quoting with the escape character \
A non-quoted backslash (\
) is the escape character. It preserves the literal value of the next character that follows, with the exception of <newline>
.
So to enter a directory or a file with a special character, escape the latter with \
, e.g.:
cd space\ dir # change into directory called “space dir”
cat space\ file # print the content of file “space file”
echo content > \\ # print “content” into file “\”
cat \( # print the content of file “(”
ls -l \? # list file “?”
bash
's Programmable Completion (aka Tab ↹ Completion) automatically escapes special characters with the escape character \
.
Quoting with double quotes " "
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $
, `
, \
, and, when history expansion is enabled, !
.
So to enter a directory or a file with a special character, escape at least the latter or a greater part of your filename or path with double quotes, e.g.:
cd space" "dir # change into directory called “space dir”
cd spac"e di"r # equally
cd "space dir" # equally
cat "space file" # print the content of file “space file”
cat "(" # print the content of file “(”
ls -l "?" # list file “?”
As $
, `
and !
keep their special meaning inside double quotes, Parameter Expansion, Command Substitution, Arithmetic Expansion and History Expansion are performed on double-quoted strings.
Quoting with single quotes ' '
Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.
So to enter a directory or a file with a special character, escape at least the latter or a greater part of your filename or path with double quotes, e.g.:
cd space' 'dir # change into directory called “space dir”
cd spac'e di'r # equal
cd 'space dir' # equal
cat 'space file' # print the content of file “space file”
cat '(' # print the content of file “(”
ls -l '?' # list file “?”
echo content > '\' # print “content” into file “\”
You can find more about Quoting in man bash
/QUOTING, on wiki.bash-hackers.org and on tldp.org.
*
" syntax magic, see also stackoverflow.com/a/51239548/287948