测试批处理文件中参数是否为空的正确方法是什么?

我需要测试是否设置了变量。我已经尝试了几种技术,但他们忽视了,只要%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.

根据本站点的介绍,这些是受支持的IF语法类型。因此,我没有找到一种方法。


IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command


当年话下
浏览 1634回答 3
3回答

牧羊人nacy

使用方括号代替引号:IF [%1] == [] GOTO MyLabel括号不安全:只能使用方括号。

千万里不及你

您可以使用:IF "%~1" == "" GOTO MyLabel去除外部引号。通常,与使用方括号相比,这是一种更可靠的方法,因为即使变量中有空格,该方法也将起作用。

FFIVE

最好的半解决方案之一是将其复制%1到变量中,然后使用延迟扩展(如delayExp)。对任何内容始终是安全的。set "param1=%~1"setlocal EnableDelayedExpansionif "!param1!"=="" ( echo it is empty )rem ... or use the DEFINED keyword nowif defined param1 echo There is something这样的好处是处理param1是绝对安全的。而且param1的设置在很多情况下都可以使用,例如test.bat hello"this is"a"testtest.bat you^&me但是它会失败,并带有诸如test.bat "&"^&为了能够获得100%正确的存在答案,您可以使用此代码块,它检测是否%1为空,但是对于某些内容,它无法获取内容。这对于区分空值%1和带的值也很有用""。它使用CALL命令的能力而不会中止批处理文件而失败。@echo offsetlocal EnableDelayedExpansionset "arg1="call set "arg1=%%1"if defined arg1 goto :arg_existsset "arg1=#"call set "arg1=%%1"if "!arg1!" EQU "#" (    echo arg1 exists, but can't assigned to a variable    REM Try to fetch it    call set arg1=%%1    goto :arg_exists)echo arg1 is missingexit /b:arg_existsecho arg1 exists, perhaps the content is '!arg1!'
打开App,查看更多内容
随时随地看视频慕课网APP