为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

当年话下 2019-12-12 14:55:56
我需要测试是否设置了变量。我已经尝试了几种技术,但他们忽视了,只要%1用双引号包围时,如情况%1是"c:\some path with spaces"。IF NOT %1 GOTO MyLabel // This is invalid syntaxIF "%1" == "" GOTO MyLabel // Works unless %1 has double quotes which fatally kills bat executionIF %1 == GOTO MyLabel // Gives an unexpected GOTO error.根据本站点的介绍,这些是受支持的IF语法类型。因此,我没有找到一种方法。IF [NOT] ERRORLEVEL number commandIF [NOT] string1==string2 commandIF [NOT] EXIST filename command
查看完整描述

3 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

使用方括号代替引号:


IF [%1] == [] GOTO MyLabel

括号不安全:只能使用方括号。


查看完整回答
反对 回复 2019-12-12
?
千万里不及你

TA贡献1784条经验 获得超9个赞

您可以使用:


IF "%~1" == "" GOTO MyLabel

去除外部引号。通常,与使用方括号相比,这是一种更可靠的方法,因为即使变量中有空格,该方法也将起作用。


查看完整回答
反对 回复 2019-12-12
?
FFIVE

TA贡献1797条经验 获得超6个赞

最好的半解决方案之一是将其复制%1到变量中,然后使用延迟扩展(如delayExp)。对任何内容始终是安全的。


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和带的值也很有用""。

它使用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

    call set arg1=%%1

    goto :arg_exists

)


echo arg1 is missing

exit /b


:arg_exists

echo arg1 exists, perhaps the content is '!arg1!'


查看完整回答
反对 回复 2019-12-12
  • 3 回答
  • 0 关注
  • 1625 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信