user34537
user34537

Reputation:

ensure 2 arguments are passed in a bat file

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.

Upvotes: 1

Views: 444

Answers (3)

Patrick Cuff
Patrick Cuff

Reputation: 29816

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.

Upvotes: 1

Daniel Pryden
Daniel Pryden

Reputation: 60997

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.

Upvotes: 1

harpo
harpo

Reputation: 43218

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.

Upvotes: 2

Related Questions