setlocal, endlocal
When you want to use variables in the command prompt or batch files, you can specify the set
command to assign a value to a specific variable name.
However, using the set
command as is treats the variable as a global variable.
Because the variable remains after the execution of the batch file, using the same variable name in other batch files or the command prompt may result in unexpected outcomes.
To prevent such issues, you can limit the scope of the variable by using the setlocal
and endlocal
commands.
How to Use the setlocal and endlocal Commands
Without Using setlocal and endlocal
As an example, create two batch files named caller.cmd and callee.cmd, as follows.
@echo off
set VAR=Hello
call callee.cmd
@echo off
echo %VAR%
When the above caller.cmd is executed, callee.cmd is run, and echo %VAR%
is executed within callee.cmd.
Since setlocal
and endlocal
are not used, the defined variable VAR
is treated as a global variable.
Therefore, it can be referenced from callee.cmd, and the string Hello
is output.
Using setlocal and endlocal
Next, we’ll modify the previously created caller.cmd and callee.cmd as follows.
@echo off
setlocal
set VAR=Hello
endlocal
call callee.cmd
@echo off
echo %VAR%
Add setlocal
and endlocal
to caller.cmd, with no changes to callee.cmd.
When you run the above caller.cmd, callee.cmd is executed, and echo %VAR%
is executed within callee.cmd.
However, because setlocal
and endlocal
are used, executing echo %VAR%
within callee.cmd does not output anything, as the VAR
variable does not exist.
When actually executed, it results in the following:
By using setlocal
and endlocal
, you can limit the scope of variables.
To prevent unintended variable references, it is recommended to use setlocal
and endlocal
when creating batch files.