如何删除一个 cmd 变量?

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

SET "FOO=bar"

除了重新使用 CMD shell 之外,还有其他方法来取消定义这个变量吗?

114939 次浏览

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=      .

This works for me in my Windows 7 CMD shell:

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

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%

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.

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