How to check command line parameter in ".bat" file?

javauser71 picture javauser71 · Feb 10, 2011 · Viewed 204.7k times · Source

My OS is Windows Vista. I need to have a ".bat" file where I need to check if user enters any command-line parameter or not. If does then if the parameter equals to -b then I will do something otherwise I will flag "Invalid input". If user does not enter any command-line parameter then I will do something. I have created following .bat file. It works for -b and not-equal to -b cases - but it fails when user does not pass any command-line parameter.

I always get error:

GOTO was unexpected at this time.

Can anyone tell me what am I doing wrong here?


ECHO OFF
CLS
ECHO.

IF [%1]==[/?] GOTO BLANK

IF %1=="-b" GOTO SPECIFIC

IF NOT %1=="-b" GOTO UNKNOWN

:SPECIFIC

ECHO SPECIFIC

GOTO DONE

:BLANK

ECHO No Parameter

GOTO DONE

:UNKNOWN

ECHO Unknown Option

GOTO DONE

:DONE

ECHO Done!

Answer

afrazier picture afrazier · Feb 10, 2011

You need to check for the parameter being blank: if "%~1"=="" goto blank

Once you've done that, then do an if/else switch on -b: if "%~1"=="-b" (goto specific) else goto unknown

Surrounding the parameters with quotes makes checking for things like blank/empty/missing parameters easier. "~" ensures double quotes are stripped if they were on the command line argument.