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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2541767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:13:56  来源:igfitidea点击:

What is the proper way to test if a parameter is empty in a batch file?

windowsshellbatch-filecmd

提问by blak3r

I need to test if a variable is set or not. I've tried several techniques but they seem to fail whenever %1is surrounded by quotes such as the case when %1is "c:\some path with spaces".

我需要测试是否设置了变量。我尝试了几种技术,但是当%1被引号包围时,它们似乎都失败了,例如 when %1is "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.

According to this site, these are the supported IFsyntax types. So, I don't see a way to do it.

根据此站点,这些是受支持的IF语法类型。所以,我看不出有什么办法做到这一点。

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

回答by Dan Story

Use square brackets instead of quotation marks:

使用方括号代替引号:

IF [%1] == [] GOTO MyLabel

Parentheses are insecure: only use square brackets.

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

回答by jamesdlin

You can use:

您可以使用:

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.

去除外部引号集。一般来说,这是比使用方括号更可靠的方法,因为即使变量中有空格它也能工作。

回答by jeb

One of the best semi solutions is to copy %1into a variable and then use delayed expansion, as delayedExp. is always safe against any content.

最好的半解决方案之一是复制%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

The advantage of this is that dealing with param1 is absolutly safe.

这样做的好处是处理 param1 是绝对安全的。

And the setting of param1 will work in many cases, like

并且 param1 的设置在很多情况下都有效,比如

test.bat hello"this is"a"test
test.bat you^&me

But it still fails with strange contents like

但它仍然以奇怪的内容失败,例如

test.bat ^&"&

To be able to get a 100% correct answer for the existence

能够得到100%正确答案的存在

It detects if %1is empty, but for some content it can't fetch the content.
This can be also be useful to distinguish between an empty %1and one with "".
It uses the ability of the CALLcommand to fail without aborting the batch file.

它检测是否%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 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!'

If you want to be 100% bullet proof to fetch the content, you could read How to receive even the strangest command line parameters?

如果您想 100% 防弹以获取内容,您可以阅读如何接收最奇怪的命令行参数?

回答by Andy Morris

From IF /?:

从 IF /?:

If Command Extensions are enabled IF changes as follows:

IF [/I] string1 compare-op string2 command
IF CMDEXTVERSION number command
IF DEFINED variable command

......

The DEFINED conditional works just like EXISTS except it takes an environment variable name and returns true if the environment variable is defined.

如果启用命令扩展,则 IF 更改如下:

IF [/I] string1 compare-op string2 command
IF CMDEXTVERSION number command
IF DEFINED variable command

......

DEFINED 条件的工作方式与 EXISTS 类似,但它采用环境变量名称,如果定义了环境变量,则返回 true。

回答by AutoMattTick

Unfortunately I don't have enough reputation to comment or vote on the current answers to I've had to write my own.

不幸的是,我没有足够的声誉来评论或投票我不得不自己写的当前答案。

Originally the OP's question said "variable" rather than "parameter", which got very confusing, especially as this was the number one link in google for searching how to test for blank variables. Since my original answer, Stephan has edited the original question to use the correct terminology, but rather than deleting my answer I decided to leave it to help clear up any confusion, especially in case google is still sending people here for variables too:

最初 OP 的问题说的是“变量”而不是“参数”,这很令人困惑,尤其是因为这是 google 中搜索如何测试空白变量的第一个链接。自从我的原始答案以来,Stephan 已经编辑了原始问题以使用正确的术语,但我决定保留它以帮助消除任何混淆,而不是删除我的答案,尤其是在谷歌仍然向这里发送变量的情况下:

%1 IS NOT A VARABLE! IT IS A COMMAND LINE PARAMETER.

%1 不是变量!这是一个命令行参数。

Very important distinction. A single percent sign with a number after it refers to a command line parameter not a variable.

非常重要的区别。后面带有数字的单个百分号指的是命令行参数而不是变量。

Variables are set using the set command, and are recalled using 2 percent signs - one before and one after. For example %myvar%

变量使用 set 命令设置,并使用 2% 符号调用 - 一个之前和一个之后。例如 %myvar%

To test for an empty variable you use the "if not defined" syntax (commands explicitly for variables do not require any percent signs), for example:

要测试空变量,请使用“if not defined”语法(显式用于变量的命令不需要任何百分号),例如:

set myvar1=foo  
if not defined myvar1 echo You won't see this because %myvar1% is defined.  
if not defined myvar2 echo You will see this because %myvar2% isn't defined.

(If you want to test command line parameters then I recommend referring to jamesdlin's answer.)

(如果你想测试命令行参数,那么我建议参考 jamesdlin 的回答。)

回答by zackz

Use "IF DEFINED variable command" to test variable in batch file.

使用“IF DEFINED variable command”来测试批处理文件中的变量。

But if you want to test batch parameters, try below codes to avoid tricky input (such as "1 2" or ab^>cd)

但是如果你想测试批处理参数,请尝试以下代码以避免棘手的输入(例如“1 2”或ab^>cd)

set tmp="%1"
if "%tmp:"=.%"==".." (
    echo empty
) else (
    echo not empty
)

回答by Kate

I test with below code and it is fine.

我用下面的代码测试,没问题。

@echo off

set varEmpty=
if not "%varEmpty%"=="" (
    echo varEmpty is not empty
) else (
    echo varEmpty is empty
)
set varNotEmpty=hasValue
if not "%varNotEmpty%"=="" (
    echo varNotEmpty is not empty
) else (
    echo varNotEmpty is empty
)

回答by noname

You can use

您可以使用

if defined (variable) echo That's defined!
if not defined (variable) echo Nope. Undefined.

回答by aphoria

I usually use this:

我通常使用这个:

IF "%1."=="." GOTO MyLabel

If %1 is empty, the IF will compare "." to "." which will evaluate to true.

如果 %1 为空,IF 将比较“.” 到 ”。” 这将评估为真。

回答by kayleeFrye_onDeck

I created this small batch script based on the answers here, as there are many valid ones. Feel free to add to this so long as you follow the same format:

我根据这里的答案创建了这个小批量脚本,因为有很多有效的。只要您遵循相同的格式,就可以随意添加:

REM Parameter-testing

Setlocal EnableDelayedExpansion EnableExtensions

IF NOT "%~1"=="" (echo Percent Tilde 1 failed with quotes) ELSE (echo SUCCESS)
IF NOT [%~1]==[] (echo Percent Tilde 1 failed with brackets) ELSE (echo SUCCESS)
IF NOT  "%1"=="" (echo Quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1]==[] (echo Brackets one failed) ELSE (echo SUCCESS)
IF NOT "%1."=="." (echo Appended dot quotes one failed) ELSE (echo SUCCESS)
IF NOT [%1.]==[.] (echo Appended dot brackets one failed) ELSE (echo SUCCESS)

pause