我正在尝试将一些可选参数添加到批处理文件中,但遇到了麻烦,因为 SHIFT
命令不会影响 all-arguments 变量 % *
。
如果我必须使用 %*
,有谁知道如何允许可选的批处理文件参数?
例如,一个简单的示例,它仅使用换行符和不换行符将参数打印到屏幕上,使用可选参数来确定哪个:
@echo off
if (%1)==() goto usage
if (%1)==(/n) goto noeol
goto eol
:eol
echo %*
goto :eof
:noeol
shift
call showline %*
goto :eof
:usage
echo Prints text to the screen
echo > %0 [/n] TEXT
echo /n to NOT print a new-line at the end of the text
goto :eof
最佳答案
如您所知,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
语句,中间用与号 (&) 分隔。 &
告诉命令处理器后面要执行一个单独的命令。
编辑:
仅供引用:我建议在检查变量内容时使用双引号。 通常您可以使用任何 字符,您甚至不需要使用两个字符,因为它们只是为了确保空变量不会导致错误。例如,当 %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
。
关于batch-file - SHIFT 不影响 %*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12990480/