Sign up ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is it considered necessary or good practice to unload variables used in Windows batch files?
For example in the following code, is the set myFolder= at the end necessary?

@echo off
set myFolder="C:\Temp\Batchfiles"
echo %myFolder%

set myFolder=

I have seen this in a number of places online, surely the variables are unloaded automatically when the batch file ends?

share|improve this question

1 Answer 1

up vote 24 down vote accepted

SET will set a global environment variable. It will persist after the execution of your script.

Let's have a look at an example.
First, I clear the variable to make sure it doesn't exist.

C:\Users\Oliver\Desktop>set TEST=

A quick test:

C:\Users\Oliver\Desktop>echo %TEST%

Let's create that batch file and execute it:

C:\Users\Oliver\Desktop>echo set TEST=something>test.bat
C:\Users\Oliver\Desktop>set TEST=something

Let's see the value of TEST after the execution of my .bat file:

C:\Users\Oliver\Desktop>echo %TEST%

So, yes, clearing the variable at the end of the script is good practice.

Even better would be to use SETLOCAL and ENDLOCAL to avoid the whole problem.

Here, I created a new .bat file that uses SETLOCAL and ENDLOCAL:

C:\Users\Oliver\Desktop>type test.bat
set TEST=something

Let's clear TEST and echo it to make sure we start clean:

C:\Users\Oliver\Desktop>set TEST=
C:\Users\Oliver\Desktop>echo %TEST%

Great, now let's run the new .bat:

C:\Users\Oliver\Desktop>set TEST=something    

Now TEST will still be empty:

C:\Users\Oliver\Desktop>echo %TEST%
share|improve this answer
+! for the clarification – Raystafarian Mar 5 '12 at 12:27
Great example and explanation - thanks – ChrisB Mar 6 '12 at 10:18

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.