测试批处理文件中的参数是否为空的正确方法是什么? [英] What is the proper way to test if a parameter is empty in a batch file?
问题描述
我需要测试是否设置了变量.我已经尝试了几种技术,但是当 %1
被引号包围时它们似乎都失败了,例如 %1
是 "c:some path带空格"
.
I need to test if a variable is set or not. I've tried several techniques but they seem to fail whenever %1
is surrounded by quotes such as the case when %1
is "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
语法类型.所以,我没有办法做到这一点.
According to this site, these are the supported IF
syntax types. So, I don't see a way to do it.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
更新:在 2020 年 10 月 25 日,我将接受的答案从使用括号更新为使用波浪号.每个人都说波浪号更好,因为它更安全.我有点不明白,因为波浪号看起来更复杂,而且不太清楚它的用途是什么,但尽管如此,我还是改变了它.
UPDATE: on 2020-10-25, I updated the accepted answer from using brackets to using a tilde. Everyone says the tilde is better as it's more secure. I'm a little torn cause the tilde looks more complicated and is less clear as to what it's purpose is but nevertheless, I changed it.
推荐答案
您可以使用:
IF "%~1" == "" GOTO MyLabel
去除外部引号集.一般来说,这是比使用方括号更可靠的方法,因为即使变量中有空格它也能工作.
to strip the outer set of quotes. In general, this is a more reliable method than using square brackets because it will work even if the variable has spaces in it.
这篇关于测试批处理文件中的参数是否为空的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!