pyk*_*yko 89 shell scripting batch-file
只是将一些shell脚本转换为批处理文件,有一件事我似乎找不到......这是一个简单的命令行参数数量.
例如.如果你有:
myapp foo bar
Run Code Online (Sandbox Code Playgroud)
在壳牌:
批量生产
所以我环顾四周,要么我正在寻找错误的地方,要么我是盲目的,但我似乎无法找到一种方法来获取传入的命令行参数的数量.
是否有类似于shell的"$#"命令用于批处理文件?
PS.我发现最接近的是遍历%1s并使用'shift',但是我需要在脚本中稍后引用%1,%2等,这样就没有用了.
nim*_*odm 94
谷歌搜索从wikibooks得到以下结果:
set argC=0
for %%x in (%*) do Set /A argC+=1
echo %argC%
Run Code Online (Sandbox Code Playgroud)
好像cmd.exe已经从旧的DOS时代发展了一下:)
Dea*_*vey 40
您倾向于使用这种逻辑处理多个参数:
IF "%1"=="" GOTO HAVE_0
IF "%2"=="" GOTO HAVE_1
IF "%3"=="" GOTO HAVE_2
Run Code Online (Sandbox Code Playgroud)
等等
如果你有超过9个参数,那么你会被这种方法搞砸.你可以在这里找到各种用于创建计数器的黑客,但要警告这些不适合胆小的人.
pax*_*blo 18
以下功能:getargc可能是您正在寻找的.
@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
Run Code Online (Sandbox Code Playgroud)
它基本上在列表上迭代一次(这是函数的本地函数,因此移位不会影响主程序中的列表),计算它们直到它用完为止.
它还使用了一个漂亮的技巧,传递了由函数设置的返回变量的名称.
主程序只是说明如何调用它并在之后回显参数以确保它们不受影响:
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"
Run Code Online (Sandbox Code Playgroud)
小智 7
试试这个:
SET /A ARGS_COUNT=0
FOR %%A in (%*) DO SET /A ARGS_COUNT+=1
ECHO %ARGS_COUNT%
Run Code Online (Sandbox Code Playgroud)
如果参数的数量应该是一个确切的数字(小于或等于9),那么这是一种检查它的简单方法:
if "%2" == "" goto args_count_wrong
if "%3" == "" goto args_count_ok
:args_count_wrong
echo I need exactly two command line arguments
exit /b 1
:args_count_ok
Run Code Online (Sandbox Code Playgroud)