Reputation: 33618
If you have a filename containing spaces, you typically double quote it on the Windows command shell (cmd.exe
).
dir "\Program Files"
This also works for other special characters like ^&;,=
. But it doesn't work for percent signs as they may be part of variable substitution. For example,
mkdir "%os%"
will create a directory named Windows_NT
. To escape the percent sign, a caret can be used:
mkdir ^%os^%
But unfortunately, the caret sign loses its meaning in double quotes:
mkdir "^%os^%"
creates a directory named ^%os^%
.
This is what I found out so far (Windows 7 command shell):
^
and &
can be escaped with either a caret or double quotes.;
, ,
, =
, and space can only be escaped with double quotes.%
can only be escaped with a caret.'`+-~_.!#$@()[]{}
apparently don't have to be escaped in filenames.<>:"/\|?*
are illegal in filenames anyway.This seems to make a general algorithm to quote filenames rather complicated. For example, to create a directory named My favorite %OS%
, you have to write:
mkdir "My favorite "^%OS^%
Question 1: Is there an easier way to safely quote space and percent characters?
Question 2: Are the characters '`+-~_.!#$@()[]{}
really safe to use without escaping?
Upvotes: 6
Views: 13373
Reputation: 7921
^
and &
can be escaped with either a caret or double quotes.There is an additional restriction when piping.
When a pipe is used, the expressions are parsed twice. First when the expression before the pipe is executed and a second time when the expression after the pipe is executed. So to escape any characters in the second expression double escaping is needed:
The line below will echo a single
&
character:break| echo ^^^&
%
can only be escaped with a caret.%
can also be escaped by doubling it.
The
%
character has a special meaning for command line parameters andFOR
parameters.To treat a percent as a regular character, double it:
%%
mkdir "My favorite "^%OS^%
Question 1: Is there an easier way to safely quote space and percent characters?
Use %%
instead of %
with the second "
at the end where you would normally expect it to be.
C:\test\sub>dir
...
Directory of C:\test\sub
03/06/2015 14:40 <DIR> .
03/06/2015 14:40 <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 82,207,772,672 bytes free
C:\test\sub>mkdir "My favorite %%OS%%"
C:\test\sub>dir
...
Directory of C:\test\sub
03/06/2015 14:40 <DIR> .
03/06/2015 14:40 <DIR> ..
03/06/2015 14:40 <DIR> My favorite %Windows_NT%
0 File(s) 0 bytes
3 Dir(s) 82,207,772,672 bytes free
Question 2: Are the characters '`+-~_.!#$@()[]{} really safe to use without escaping?
No, again there are some additional circumstances when some of these must be escaped, for example when using delayed variable expansion or when using for /f
.
See Escape Characters for all the details ... in particular the Summary table.
Sources Syntax : Escape Characters, Delimiters and Quotes and Escape Characters.
Upvotes: 8