windows 如何检查批处理文件中是否存在变量?

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

How to check if a variable exists in a batch file?

windowsbatch-filecmd

提问by Fivos Capone

I am using the callcommand:

我正在使用call命令:

call beingcalled.bat randomnumber

In beingcalled.bat:

在被调用.bat 中

@echo off
set call=%1
echo %call%
set call=%call%%call%
call caller.bat %call%`

In caller.bat:

caller.bat 中

@echo off
set calltwo=%1
echo %calltwo%
if "%calltwo%"== "" (
    echo Error
) else (
    call beingcalled.bat randomnumber
)

Why does the command if "%calltwo%"== ""not work? And how do I see if a variable was set?

为什么命令if "%calltwo%"== ""不起作用?以及如何查看是否设置了变量?

回答by Rishav

IF "%Variable%"=="" ECHO Variable is NOT defined

This should help but this works, provided the value of Variable does not contain double quotes. Or you may try. Both worked for me.

如果 Variable 的值不包含双引号,这应该会有所帮助,但这是有效的。或者你可以试试。两者都对我来说有效。

VERIFY OTHER 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 ECHO Unable to enable extensions
IF DEFINED MyVar (ECHO MyVar IS defined) ELSE (ECHO MyVar is NOT defined)
ENDLOCAL

source http://www.robvanderwoude.com/battech_defined.php

来源http://www.robvanderwoude.com/battech_defined.php

回答by K4dse

The easiest way is just using the command line extension DEFINED. This is also my preferred way of doing this.

最简单的方法是使用命令行扩展定义。这也是我的首选方式。

in your case:

在你的情况下:

@echo off
set calltwo=%1
echo %calltwo%
if defined calltwo (
echo Error
)else (
call beingcalled.bat randomnumber
)

If this doesn't work for you there is a workaround in the link below.

如果这对您不起作用,下面的链接中有一个解决方法。

The question is also a duplicate of: Check if an environment variable is defined without command extensions and without using a batch file?

这个问题也是重复的:检查是否在没有命令扩展和没有使用批处理文件的情况下定义了环境变量?

回答by Philip Kelley

This is just a follow-up to the comment (and bounty) post by @Rishav

这只是@Rishav 的评论(和赏金)帖子的后续行动

Here's a trick I picked up a very long time ago:

这是我很久以前学到的一个技巧:

@ECHO OFF

SET Foo=%1

ECHO ==  Start  ====================

ECHO %Foo%

IF %Foo%x == x ECHO Parameter not set

ECHO ==  End  ====================
ECHO.

If the parameter is not set, you get a check of x==x

如果没有设置参数,你会得到一个检查 x==x

If the parameter is set (to, say, “asdf”), you get a check of asdfx==x

如果参数被设置(比如,“asdf”),你会得到一个检查 asdfx==x