How do I remove a cmd variable?

Batch FileCmd

Batch File Problem Overview


Let's say I execute the following in the CMD shell:

SET "FOO=bar"

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

Batch File Solutions


Solution 1 - Batch File

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

Solution 2 - Batch File

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%

Solution 3 - Batch File

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.

Solution 4 - Batch File

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

Solution 5 - Batch File

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser288004View Question on Stackoverflow
Solution 1 - Batch FileMadara's GhostView Answer on Stackoverflow
Solution 2 - Batch FilejebView Answer on Stackoverflow
Solution 3 - Batch Filewalid2miView Answer on Stackoverflow
Solution 4 - Batch FilePekkaView Answer on Stackoverflow
Solution 5 - Batch FiledgoView Answer on Stackoverflow