Reputation: 9475
Running the following minimal example:
(
echo if "%%1" == "" (
echo echo Success ^|^| goto :fail
echo ^) else (
echo echo Failure ^|^| goto :fail
echo ^)
) >"testresult.bat"
call "testresult.bat" "first 1" --flag="other options" --verbose
Results the following as contents of testresult.bat
:
if "%1" == "" (
echo Success || goto :fail
) else (
echo Failure || goto :fail
)
And calling testresult.bat
with the command line arguments "first 1" --flag="other options" --verbose
gives me:
C:\User>test.bat
C:\User>(
echo if "%1" == "" (
echo echo Success || goto :fail
echo ) else (
echo echo Failure || goto :fail
echo )
) 1>"testresult.bat"
C:\User>call "testresult.bat" "first 1" --flag="other options" --verbose
1"" was unexpected at this time.
C:\User>if ""first 1"" == "" (
C:\User>
The error 1"" was unexpected at this time.
is caused because my first arguments has a double quotes.
How can I properly write my if "%1" == ""
to check whether the first argument is empty, regardless it has double quotes or not?
Upvotes: 1
Views: 1394
Reputation: 49167
The issue here is referencing argument 1 with "%1"
instead of "%~1"
.
The help output on running in a Windows command prompt window call /?
explains that %1
references the first argument as passed to the batch file without or with being enclosed in double quotes.
For that reason passing the string "first 1"
as first argument to the created batch file results in an IF condition with ""first 1""
left to comparison operator ==
which is a serious syntax error on the IF condition.
The usually used solution is using "%~1"
on IF command line. The modifier ~
results in removing surrounding "
from first argument string if there are surrounding double quotes at all. So the first string on IF condition is now nearly always correct enclosed with one pair of double quotes.
The batch file can be called with if "%~1" == ""
with first argument being:
argument1
... not quoted argument string because of "
not necessary."argument 1"
... quoted argument string because of space character.""
... empty string as argument string."argument 1
... not correct quoted argument string with space character working nevertheless on using %~1
as the single "
at beginning is removed in this case.argument1"
... not correct quoted argument string."
at end of the not correct specified argument string resulting in a syntax error on command line if "%~1" == ""
because of resulting command line is if "argument1"" == ""
.See my answer on What is the difference between "…" and x"…" in an IF condition in a Windows batch file? It explains in detail how to write a batch file which works even on last argument example.
Upvotes: 3