views:

214

answers:

2

I'm trying to use the following validation logic in a batch file but the "usage" block never executes even when no parameter is supplied to the batch file.

if ("%1"=="") goto usage

@echo This should not execute

@echo Done.
goto :eof

:usage
@echo Usage: %0 <EnvironmentName>
exit 1

What am I doing wrong?

+4  A: 

The check for whether a commandline argument has been set can be [%1]==[] but, as Dave Costa points out, "%1"=="" will also work.

I also fixed a syntax error in the usage echo to escape the greater-than and less-than signs. In addition, the exit needs a /B argument otherwise CMD.EXE will quit.

@echo off

if [%1]==[] goto usage
@echo This should not execute
@echo Done.
goto :eof
:usage
@echo Usage: %0 ^<EnvironmentName^>
exit /B 1
Iain
+4  A: 

Get rid of the parentheses.

Sample batch file:

echo "%1"

if ("%1"=="") echo match1

if "%1"=="" echo match2

Output from running above script:

C:\>echo "" 
""

C:\>if ("" == "") echo match1 

C:\>if "" == "" echo match2 
match2

I think it is actually taking the parens to be part of the strings to be compared.

Dave Costa
Well noted. Thanks!
Daniel Fortunov