您可以使用%1
,%2
等来表示单独的命令行参数。在您的情况下,--port
将是%3
,其值将是%4
。
幸运的是,还有一个shift
命令,它会将所有参数都向左移动,2变成1,3变成2等等。
这意味着您可以在循环中“抓取”所有命令行参数。您不断地进行移位,并且当您遇到--port
时,您就知道下一个参数将是端口号,您可以将其存储在适当的变量中(使用set
)以备后用。
如果您按照这种方式实现,您可以实现一堆可选参数,而且顺序也不重要。
因此,在代码中,您的'foo.bat'可能如下所示:
@echo off
:: No parameters given? Then run ourselves with the defaults from the question.
if "%1"=="" goto none
:: Actual reading of parameters starts here.
:loop
if "%1"=="--port" set port=%2
:: Of course you need the other ifs only if you're interested in these parameters
if "%1"=="--foo" set foo=%2
if "%1"=="--bar" set bar=%2
:: Shift all parameters, except %0. Do it twice to skip the parameter and its value.
shift /1
shift /1
:: As long as there are more, keep looping. You can even parse more than 10 parameters this way!
if not "%1"=="" goto loop
:: Output what we've found
echo The specified port is %port%
echo Foo is set to %foo%
echo The bar is at %bar%
pause
exit /b
:: If no parameters are given, call ourselves with example parameters.
:none
call %0 --foo bar --port 80 --bar foo
这是一种简化版本,没有仅显示端口号的演示废话。我认为这是您当前代码的替代方案。
@echo off
:loop
if "%1"=="--port" set port=%2
shift /1
shift /1
if not "%1"=="" goto loop
echo %port%
="
将其替换为空。但是,结尾的&:
对我来说很迷惑。 - kevinmm"&:"
,因此在变量扩展后整行变成了@Set "PORT_NUM=80"&:""
;&
允许在同一行上连接另一个命令,剩下的:""
只是一个跳转标签,所以被忽略了... - aschipflfoo.bat --foo --port --port 80 --bar foo
将产生 port=--port 的结果。 - dbenham