Reno

Source: Compression Project

A well-written DOS batch file should always check the number of command line arguments passed to it even if it doesn’t require any arguments.  If the actual number of arguments doesn’t match the expected number of arguments, then display a usage message to ensure that the user understands what the batch file is supposed to do.

The DOS batch file below shows you how to determine the total number of command line arguments given by the user during invocation.  In this example, we expect two arguments only, but the user provides three.  A usage message is displayed and an exit status of 1 is returned to the operating system.  We run the batch file again, but this time with the correct number of arguments.  No usage message is displayed and an exit status of 0 is returned instead.

[CODE]:

@echo off

set _exitStatus=0
set _argcActual=0
set _argcExpected=2

echo.

for %%i in (%*) do set /A _argcActual+=1

if %_argcActual% NEQ %_argcExpected% (

  call :_ShowUsage %0%, "Bad human...bad args."
  
  set _exitStatus=1
  
  goto:_EOF
)

REM Your code goes here

goto:_EOF

:_ShowUsage
  
  echo [USAGE]: %~1 arg1 arg2

  echo.
  
  if NOT "%~2" == "" (

    echo %~2
    
    echo.
  )
  
  goto:eof

:_EOF
 
echo The exit status is %_exitStatus%.

echo.

cmd /c exit %_exitStatus%

[OUTPUT]:

c:\>countargs.bat 1 2 3

[USAGE]: countargs.bat arg1 arg2

Bad human...bad args.

The exit status is 1.

c:\>countargs.bat 1 2

The exit status is 0.

c:\>
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)