Celeb Glow
updates | March 05, 2026

Parsing command line argument in BATCH file

I have picked up following example to understand parsing of command line argument in BATCH file:

@echo off
:Help
echo sumit
:GETOPTS
if /I "%1" == "-h" call :Help
if /I "%1" == "-b" set BASE=%2 & shift
if /I "%1" == "-s" set SQL=%2 & shift
shift
if not "%1" == "" goto GETOPTS
echo %BASE%
echo %SQL%

Now, have few issues with it, :Help is called even if I don't pass -h option to my batch file during execution.

How it could be avoided ?

optgets.bat -b milan -s okaz
sumit
milan
okaz

It shouldn't print sumit as I didn't pass -h option

Second, once done with execution it should unset the variable being set using command line arguments

1

2 Answers

Just in order to debug your original Source Code File, you can simply skip the initial echo Command using a goto Command:

@echo off
goto GETOPTS
:Help
echo sumit
:GETOPTS
if /I "%1" == "-h" call :Help
if /I "%1" == "-b" set BASE=%2 & shift
if /I "%1" == "-s" set SQL=%2 & shift
shift
if not "%1" == "" goto GETOPTS
echo %BASE%
echo %SQL%

Can you please explain what you have meant through the following paragraph?

Second, once done with execution it should unset the variable being set using command line arguments.

This batch file will always do the echo sumit since it is the first thing in the file.

You surely meant something like:

@echo off
:GETOPTS
if /I "%1" == "-h" goto Help
if /I "%1" == "-b" set BASE=%2 & shift
if /I "%1" == "-s" set SQL=%2 & shift
shift
if not "%1" == "" goto GETOPTS
echo %BASE%
echo %SQL%
exit
:Help
echo sumit
exit

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy