2

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

3 Answers 3

3

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.

3

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
0

Just because something is under a label doesn't mean that the label is treated like a function to be called. You would need to use a goto GETOPTS before the :help line. (cmd.exe doesn't have the concept of 'call', either, so you'd need to use goto where you currently have call.)

For your second question, it is possible to make environment changes local to the cmd file (or even regions of the cmd file) by using the SETLOCAL command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .