I'm sure you are aware that %1
, %2
, etc. inside a .bat represent the numbered arguments passed to the .bat on the commandline.
If you use them as %~1
, %~2
, etc. all surrounding quotes will be removed automatically, should they be there.
Consider this space-in-args.bat
for testing:
@echo off
echo. %1
echo. (original first argument echo'd)
echo.
echo. "%1"
echo. (original first argument with additional surrounding quotes)
echo.
echo. %~1
echo. (use %%~1 instead of %%1 to remove surrounding quotes, should there be)
echo.
echo. "%~1"
echo. (we better use "%%~1" instead of "%%1" in this case:
echo. 1. ensure, that argument is quoted when used inside the batch;
echo. 2. avoid quote doubling should the user have already passed quotes.
echo.
Run it:
space-in-args.bat "a b c d e"
Output is:
"a b c d e"
(original first argument echo'd)
""a b c d e""
(original first argument with additional surrounding quotes)
a b c d e
(using %~1 instead of %1 removes surrounding quotes, should there be some)
"a b c d e"
(we better use "%~1" instead of "%1" in this case:
1. ensure, that argument is quoted when used inside the batch;
2. avoid quote doubling should the user have already passed quotes.
See also for /?
(scroll down towards the end) to find out about some more of those conversions.