views:

32

answers:

3

How do i ensure 2 arguments are passed in a bat file?

I would like to echo a description of the arguments and exit the bat if there are not exactly 2 arguments.

+2  A: 

See Note 1 on this page about the need for a dummy when testing for empty strings.

IF dummy-==dummy-%1 (
    ECHO Syntax is blah blah
    EXIT /B
)

IF dummy-==dummy-%2 (
    ECHO Syntax is blah blah
    EXIT /B
)

Also I find this is a good reference when writing batch files.

harpo
Per @Daniel's answer, I reckon the first check is redundant.
harpo
I wrote IF dummy-==dummy-%2 ( ECHO Blah EXIT /B)IF NOT dummy-==dummy-%3 ( ECHO To many arguments EXIT /B)
acidzombie24
That `dummy-` syntax is ugly and adds no value. CMD.EXE will compare the strings on either side of `==` character for character (after stripping leading and trailing whitespace), so you might as well say `if FOOBAR==FOO%1BAR` since it means the same thing. But my preference is to use quote characters since it's much more legible.
Daniel Pryden
@Daniel, I agree your syntax looks better, but the quotes serve essentially the same purpose; that is, they add no semantic value but adjust for a syntactic consideration.
harpo
+1  A: 

Do

if "%2"=="" goto :usage

and then put your usage text at the bottom, after a :usage label. Just make sure you exit your script with goto :eof so you don't get the usage upon normal completion.

Daniel Pryden
+1  A: 

Here's another way using the for command:

@echo off

set /a argCount=0
for %%A in (%*) do set /a argCount+=1

@echo Number of args is: %argCount%

if %argCount% NEQ 2 (
    @echo Usage
    exit /b
)

This style will handle cases where you need to ensure you have more than 9 arguments.

Patrick Cuff