Batch files - number of command line arguments

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

    The last answer was two years ago now, but I needed a version for more than nine command line arguments. May be another one also does...

    @echo off
    setlocal
    
    set argc_=1
    set arg0_=%0
    set argv_=
    
    :_LOOP
    set arg_=%1
    if defined arg_ (
      set arg%argc_%_=%1
      set argv_=%argv_% %1
      set /a argc_+=1
      shift
      goto _LOOP
    )
    ::dont count arg0
    set /a argc_-=1
    echo %argc_% arg(s)
    
    for /L %%i in (0,1,%argc_%) do (
      call :_SHOW_ARG arg%%i_ %%arg%%i_%%
    )
    
    echo converted to local args
    call :_LIST_ARGS %argv_%
    exit /b
    
    
    :_LIST_ARGS
    setlocal
    set argc_=0
    echo arg0=%0
    
    :_LOOP_LIST_ARGS
    set arg_=%1
    if not defined arg_ exit /b
    set /a argc_+=1
    call :_SHOW_ARG arg%argc_% %1
    shift
    goto _LOOP_LIST_ARGS
    
    
    :_SHOW_ARG
    echo %1=%2
    exit /b
    

    The solution is the first 19 lines and converts all arguments to variables in a c-like style. All other stuff just probes the result and shows conversion to local args. You can reference arguments by index in any function.

提交回复
热议问题