Windows 批处理文件:如果其他

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5683583/
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 08:17:15  来源:igfitidea点击:

Windows Batch Files: if else

windowsbatch-file

提问by MxLDevs

I'm doing a simple batch file that requires one argument (you can provide more, but I ignore them).

我正在做一个需要一个参数的简单批处理文件(您可以提供更多参数,但我忽略它们)。

For testing, this is what I have so far.

为了测试,这就是我到目前为止所拥有的。

if not %1 == "" (
    dir /s/b %1
) else (
    echo no
)

Basically, I want to say if an argument is provided, recursively display all the files in the folder. Otherwise, say no.

基本上,我想说如果提供了一个参数,递归地显示文件夹中的所有文件。否则,说不。

It works when I provide an argument, but if I don't provide one it'll just tell me ( was unexpected at this time.

当我提供一个参数时它会起作用,但如果我不提供一个它就会告诉我( was unexpected at this time

I mean, it works, but I wanted to at least display a user-friendly message explaining why it doesn't work. How should I change the code?

我的意思是,它有效,但我想至少显示一条用户友好的消息,解释为什么它不起作用。我应该如何更改代码?

回答by schnaader

if not %1 == "" (

must be

必须是

if not "%1" == "" (

If an argument isn't given, it's completely empty, not even ""(which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.

如果没有给出参数,则它完全是空的,甚至不是""(在大多数编程语言中表示空字符串)。所以我们使用周围的引号来检测空参数。

回答by jwd

Surround your %1with something.

%1用东西包围你。

Eg:

例如:

if not "%1" == ""

Another one I've seen fairly often:

另一个我经常看到的:

if not {%1} == {}

And so on...

等等...

The problem, as you can likely guess, is that the %1is literally replaced with emptiness. It is not 'an empty string' it is actually a blank spot in your source file at that point.

正如您可能猜到的那样,问题%1是实际上被空虚所取代。它不是“空字符串”,此时它实际上是源文件中的空白点。

Then after the replacement, the interpreter tries to parse the ifstatement and gets confused.

然后在替换后,解释器尝试解析if语句并感到困惑。

回答by David angulo

You have to do the following:

您必须执行以下操作:

if "%1" == "" (
    echo The variable is empty
) ELSE (
    echo The variable contains %1
)

回答by Darin

Another related tip is to use "%~1" instead of "%1". Type "CALL /?" at the command line in Windows to get more details.

另一个相关提示是使用“%~1”而不是“%1”。输入“呼叫/?” 在 Windows 的命令行中获取更多详细信息。

回答by mivk

An alternative would be to set a variable, and check whether it is defined:

另一种方法是设置一个变量,并检查它是否已定义:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1directly with DEFINEDdoesn't work.

不幸的是,%1直接使用 withDEFINED不起作用。

回答by skchoe

you have to do like this...

你必须这样做...

if not "A%1" == "A"

如果不是“A%1”==“A”

if the input argument %1 is null, your code will have problem.

如果输入参数 %1 为空,你的代码就会有问题。