如你所知,shift
有没有影响%*
,但你可以构造一个%*等价物。
我们称以下line.bat
:
@echo off
set line=%1
:loop
shift
if not "%1"=="" (
set line=%line% %1
goto :loop
)
echo %%* = %*
echo line = %line%
如果在键入以下命令(注意:3之间的双空间和4):
line 1 2 3 4 bla dee dah
你会得到以下输出:
%* = 1 2 3 4 bla dee dah
line = 1 2 3 4 bla dee dah
请注意,%*
保留多个空格,而使用%n
表示法不会。
使用类似这样的东西,您可以允许您的用户以任意顺序放置其参数。
:loop
:: Single variable parameters
if "%1"=="something" set something=true
:: Multi variable parameters
if "%~1"=="/source" shift & set source=%1
shift
if not "%~1"=="" goto :loop
注意的是,在多变量参数声明我包括一个shift
语句和由符号(&)分隔的一个set
语句。 &
告诉命令处理器一个单独的命令被执行。
编辑:
FYI:我检查变量的内容时,建议双引号。 通常你可以使用任何字符,你甚至不需要使用两个,因为他们只是在那里,以确保一个空的变量不会导致错误。例如,当%1
为空且您做了if not hello==%1 call :sub
时,命令处理器将看到此if not hello== call :sub
并将hello
与call
比较,然后尝试执行:sub
并引发错误。在这种情况下,if not xhello==x%1 call :sub
与if not "hello"=="%1" call :sub
一样好,因为空的%1
将导致命令处理器看到if not xhello==x call :sub
。比双引号其他
但使用字符会如果变量包含任何特殊字符引起问题。
使用括号作为变量分隔符(如(%1))可能会导致问题。例如,(特殊)管道字符在括号内不会很好,转义字符似乎消失了,既不是正常字符也不是逃逸字符。
括号也是特殊字符,它们本身被设计用于对不同的代码行进行分组和分隔,并且可能并不总是按预期行事。
最后,双引号本身是特殊字符专门设计用于包围其他特殊字符,允许它们充当普通字符。这就是为什么你可能会看到变量没有被引用,然后再次引用,如此。
set var="%~1" & REM This sort of thing is used to insure that a variable is quoted.
REM %~1 unquotes %1 if it is already quoted, and leaves it alone if
REM %1 is not quoted.
set "var=%~1" & REM This code assumes that `%1` contains special characters and
REM like before unquotes a quoted %1, but leaves the variable itself
REM unquoted. The double-quotes surrounding the variable and data
REM protects the command processor from any special characters that
REM exist in the data. Remember that anytime you reference `%var%`,
REM you will need to also surround the variable and data with
REM double-quotes.
快速检查报价是if exist %1 if %1==%~1 echo Unquoted
。
我刚刚被这个烧伤了。 Windows SHIFT的确很臭。 – Core