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):
- The characters
^
and&
can be escaped with either a caret or double quotes. - The characters
;
,,
,=
, and space can only be escaped with double quotes. - The character
%
can only be escaped with a caret. - The characters
'`+-~_.!#$@()[]{}
apparently don't have to be escaped in filenames. - The characters
<>:"/\|?*
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?
mkdir "My favorite %OS%"
works expected ... you don't need to escape the%
with^
%OS%
variable set? What doesecho %OS%
print?%OS%
is set. Output fromecho %OS%
isWindows_NT
My favorite %OS%
without variable substitution. When I runmkdir "My favorite %OS%"
, I get a directory namedMy favorite Windows_NT
which is not what I want.mkdir "My favorite %%OS%%"
works (with the second"
at the end where it should be).