windows 如何取消定义 MS-DOS 变量?

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

How to undefine a MS-DOS variable?

windowsbatch-filecmd

提问by user288004

Lets say I execute the following in the CMD shell:

假设我在 CMD shell 中执行以下操作:

set FOO=bar

Is there a way to undefine this variable, other than recycling the CMD shell?

除了回收 CMD shell 之外,有没有办法取消定义这个变量?

回答by Madara's Ghost

Yes, you can unset it with

是的,你可以用

set FOO=

Or explicitly using:

或明确使用:

set "FOO="

Ensure no trailing extraneous (invisible) characters come after the =sign. That is:

确保=符号后没有尾随的无关(不可见)字符。那是:

  • set FOO=is different from set FOO=??????.
  • set FOO=不同于set FOO=??????.

回答by jeb

A secure way to unset the variable is to use also quotes, then there aren't problems with trailing spaces.

取消设置变量的安全方法是也使用引号,然后尾随空格就没有问题。

set FOO=bar
echo %FOO%
set "FOO=" text after the last quote is ignored
echo %FOO%

回答by walid2mi

another method

另一种方法

@Echo oFF

setlocal
set FOO=bar
echo %FOO%
endlocal

echo %FOO%

pause

Note: This would not work on an interactive command prompt. But works in batch script.

注意:这不适用于交互式命令提示符。但适用于批处理脚本。

回答by Pekka

This works for me in my Windows 7 CMD shell:

这在我的 Windows 7 CMD shell 中对我有用:

set FOO=bar
echo %FOO% // bar
set FOO=
echo %FOO% // empty; calling "set" no longer lists it

回答by dgo

I would offer the following only as a comment, but I think it's important enough to stand on its own.

我将提供以下仅作为评论,但我认为独立站起来很重要。

A lot of the previous answers mentioned that one needs to beware of trailing spaces; and for sure that is true. However I've found that sometimes trailing spaces just want to get in there no matter what - particularly if you are doing a command line one-liner and need the space as a command separator.

很多前面的答案都提到需要注意尾随空格;并且可以肯定这是真的。但是我发现有时尾随空格无论如何都想进入那里 - 特别是如果您正在执行命令行单行并需要空格作为命令分隔符。

This is the solution to that problem:

这是该问题的解决方案:

SET FOO=Bar
echo %FOO%
:: outputs Bar
SET "FOO="
echo %FOO%
:: outputs %FOO%

By wrapping the declaration in double quotes that way, the spacing issue can be avoided entirely. This can also really useful when variables are created by concatenating to eliminate spaces in between - for example - paths, e.g:

通过以这种方式将声明括在双引号中,可以完全避免间距问题。当通过连接消除之间的空格来创建变量时,这也非常有用 - 例如 - 路径,例如:

SET A=c:\users\ && SET D=Daniel
SET P="%a%%d%"
ECHO %P%
:: outputs "C:\Users\ Daniel"
:: Notice the undesirable space there