空字符串是一对双引号
/""
,我们可以通过测试长度来进行验证:
set ARG=%1
if not defined ARG goto nomore
set CHAR=%ARG:~2,1%
if defined CHAR goto goon
接着测试它的2个字符是否与双引号
匹配:
if ^%ARG:~1,1% == ^" if ^%ARG:~0,1% == ^" goto blank
::else
goto goon
这里有一个批处理脚本,你可以试着运行一下。我认为它能正确地捕捉空字符串。
这只是一个例子,你只需要根据你的脚本自定义2(或3?)个步骤即可。
@echo off
if not "%OS%"=="Windows_NT" goto EOF
:: I guess we need enableExtensions, CMIIW
setLocal enableExtensions
set i=0
set script=%0
:LOOP
set /a i=%i%+1
set A1=%1
if not defined A1 goto nomore
:: Assumption:
:: Empty string is (exactly) a pair of double-quotes ("")
:: Step out if str length is more than 2
set C3=%A1:~2,1%
if defined C3 goto goon
:: Check the first and second char for double-quotes
:: Any characters will do fine since we test it *literally*
if ^%A1:~1,1% == ^" if ^%A1:~0,1% == ^" goto blank
goto goon
:goon
echo.args[%i%]: [%1]
shift
goto LOOP
:blank
echo.args[%i%]: [%1] is empty string
shift
goto LOOP
:nomore
echo.
echo.command line:
echo.%script% %*
:EOF
此测试结果如下:
.test.bat :: "" ">"""bl" " "< "">" (")(") "" :: ""-" " "( )"">\>" ""
args[1]: [::]
args[2]: [""] is empty string
args[3]: [">"""bl" "]
args[4]: ["< "">"]
args[5]: [(")(")]
args[6]: [""] is empty string
args[7]: [::]
args[8]: [""-" "]
args[9]: ["( )"">\>"]
args[10]: [""] is empty string
command line:
.test.bat :: "" ">"""bl" " "< "">" (")(") "" :: ""-" " "( )"">\>" ""
%1
中有偶数个双引号,if "%1" == "" GOTO MyLabel
就不会致命地终止脚本的执行。我发现,如果%1
中有奇数个双引号,则会出现以下错误并终止脚本的执行:The syntax of the command is incorrect.
下面的解决方案使用方括号来解决问题,被标记为正确答案,但似乎没有任何改善。当%1
中有奇数个双引号时,该解决方案也会出现相同的错误。 - Susam PalIF DEFINED
只能用于环境变量而不能用于脚本变量,这浪费了很多潜力! - kayleeFrye_onDeckCMD.bat arg1, , arg3
,以下内容是正确的:%2 == %arg3
。 - johny whyIF /i NOT "%var%"==""
是检查脚本变量是否已定义的几乎唯一安全方法。这比IF DEFINED %var%
难看得多 :( - kayleeFrye_onDeck