Batch files - number of command line arguments

后端 未结 8 1917
走了就别回头了
走了就别回头了 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:00

    A robust solution is to delegate counting to a subroutine invoked with call; the subroutine uses goto statements to emulate a loop in which shift is used to consume the (subroutine-only) arguments iteratively:

    @echo off
    setlocal
    
    :: Call the argument-counting subroutine with all arguments received,
    :: without interfering with the ability to reference the arguments
    :: with %1, ... later.
    call :count_args %*
    
    :: Print the result.
    echo %ReturnValue% argument(s) received.
    
    :: Exit the batch file.
    exit /b
    
    :: Subroutine that counts the arguments given.
    :: Returns the count in %ReturnValue%
    :count_args
      set /a ReturnValue = 0
      :count_args_for
    
        if %1.==. goto :eof
    
        set /a ReturnValue += 1
    
        shift
      goto count_args_for
    

提交回复
热议问题