Why unload variables in Windows batch files

13

4

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?

ChrisB

Posted 2012-03-05T12:03:22.910

Reputation: 1 087

Answers

33

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%
%TEST%

Let's create that batch file and execute it:

C:\Users\Oliver\Desktop>echo set TEST=something>test.bat
C:\Users\Oliver\Desktop>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%
something

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
setlocal
set TEST=something
endlocal

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%
%TEST%

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

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

Now TEST will still be empty:

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

Der Hochstapler

Posted 2012-03-05T12:03:22.910

Reputation: 77 228

2+! for the clarification – Raystafarian – 2012-03-05T12:27:58.523

1Great example and explanation - thanks – ChrisB – 2012-03-06T10:18:15.690