我需要测试是否设置了变量。我尝试了几种技术,但每当%1
被引号括起来时,它们似乎都失败了,比如%1
为"c:\some path with spaces"
的情况。
IF NOT %1 GOTO MyLabel // This is invalid syntax
IF "%1" == "" GOTO MyLabel // Works unless %1 has double quotes which fatally kills bat execution
IF %1 == GOTO MyLabel // Gives an unexpected GOTO error.
根据this site的说法,这些是受支持的IF
语法类型。所以,我看不到这样做的方法。
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
更新:在2020-10-25,我将接受的答案从使用括号更新为使用代字号。每个人都说波浪号更好,因为它更安全。我有点困惑,因为波浪符号看起来更复杂,也不太清楚它的用途,但尽管如此,我还是改变了它。
发布于 2010-03-30 18:54:02
您可以使用:
IF "%~1" == "" GOTO MyLabel
剥离外部的引号集合。一般来说,这是一种比使用方括号更可靠的方法,因为即使变量中有空格,它也可以工作。
发布于 2011-12-10 06:12:07
最好的半解决方案之一是将%1
复制到一个变量中,然后使用延迟扩展,如delayedExp。对任何内容都是安全的。
set "param1=%~1"
setlocal EnableDelayedExpansion
if "!param1!"=="" ( echo it is empty )
rem ... or use the DEFINED keyword now
if defined param1 echo There is something
这样做的好处是,处理param1是绝对安全的。
并且param1的设置在许多情况下都可以工作,比如
test.bat hello"this is"a"test
test.bat you^&me
但它仍然会失败,有奇怪的内容,比如
test.bat ^&"&
能够得到存在的100%正确答案
它会检测%1
是否为空,但对于某些内容,它无法获取内容。
这对于区分空的%1
和具有""
的and也很有用。
它使用CALL
命令的功能在不中止批处理文件的情况下失败。
@echo off
setlocal EnableDelayedExpansion
set "arg1="
call set "arg1=%%1"
if defined arg1 goto :arg_exists
set "arg1=#"
call set "arg1=%%1"
if "!arg1!" EQU "#" (
echo arg1 exists, but can't assigned to a variable
REM Try to fetch it a second time without quotes
(call set arg1=%%1)
goto :arg_exists
)
echo arg1 is missing
exit /b
:arg_exists
echo arg1 exists, perhaps the content is '!arg1!'
如果你想100%防弹获取内容,你可以阅读How to receive even the strangest command line parameters?
发布于 2014-08-13 22:35:58
使用"IF DEFINED variable command“测试批文件中的变量。
但是如果你想测试批量参数,尝试下面的代码来避免棘手的输入(例如"1 2“或ab^>cd)
set tmp="%1"
if "%tmp:"=.%"==".." (
echo empty
) else (
echo not empty
)
https://stackoverflow.com/questions/2541767
复制相似问题