Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch files - number of command line arguments

Just converting some shell scripts into batch files and there is one thing I can't seem to find...and that is a simple count of the number of command line arguments.

eg. if you have:

myapp foo bar

In Shell:

  • $# -> 2
  • $* -> foo bar
  • $0 -> myapp
  • $1 -> foo
  • $2 -> bar

In batch

  • ?? -> 2 <---- what command?!
  • %* -> foo bar
  • %0 -> myapp
  • %1 -> foo
  • %2 -> bar

So I've looked around, and either I'm looking in the wrong spot or I'm blind, but I can't seem to find a way to get a count of number of command line arguments passed in.

Is there a command similar to shell's "$#" for batch files?

ps. the closest i've found is to iterate through the %1s and use 'shift', but I need to refernece %1,%2 etc later in the script so that's no good.

like image 587
pyko Avatar asked Aug 18 '09 05:08

pyko


4 Answers

Googling a bit gives you the following result from wikibooks:

set argC=0
for %%x in (%*) do Set /A argC+=1

echo %argC%

Seems like cmd.exe has evolved a bit from the old DOS days :)

like image 143
nimrodm Avatar answered Sep 28 '22 17:09

nimrodm


You tend to handle number of arguments with this sort of logic:

IF "%1"=="" GOTO HAVE_0
IF "%2"=="" GOTO HAVE_1
IF "%3"=="" GOTO HAVE_2

etc.

If you have more than 9 arguments then you are screwed with this approach though. There are various hacks for creating counters which you can find here, but be warned these are not for the faint hearted.

like image 24
Dean Povey Avatar answered Sep 28 '22 18:09

Dean Povey


The function :getargc below may be what you're looking for.

@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof

:getargc
    set getargc_v0=%1
    set /a "%getargc_v0% = 0"
:getargc_l0
    if not x%2x==xx (
        shift
        set /a "%getargc_v0% = %getargc_v0% + 1"
        goto :getargc_l0
    )
    set getargc_v0=
    goto :eof

It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.

It also uses a nifty trick, passing the name of the return variable to be set by the function.

The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:

C:\Here> xx.cmd 1 2 3 4 5
    Count is 5
    Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
    Count is 11
    Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
    Count is 1
    Args are 1
C:\Here> xx.cmd
    Count is 0
    Args are
C:\Here> xx.cmd 1 2 "3 4 5"
    Count is 3
    Args are 1 2 "3 4 5"
like image 40
paxdiablo Avatar answered Sep 28 '22 16:09

paxdiablo


Try this:

SET /A ARGS_COUNT=0    
FOR %%A in (%*) DO SET /A ARGS_COUNT+=1    
ECHO %ARGS_COUNT%
like image 36
David Avatar answered Sep 28 '22 17:09

David