Thursday, 8 August 2019

Why unload variables in Windows batch files


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?



Answer



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%

No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...