Batch files - number of command line arguments

后端 未结 8 1922
走了就别回头了
走了就别回头了 2020-12-04 09:48

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.

<
8条回答
  •  既然无缘
    2020-12-04 10:16

    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"
    

提交回复
热议问题