setlocal, endlocal

Maintained on

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.

caller.cmd
@echo off

set VAR=Hello

call callee.cmd
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.

×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2024 Ribbit App Development All rights reserved.
 
C:\users\user>caller.cmd
Hello

Using setlocal and endlocal

Next, we’ll modify the previously created caller.cmd and callee.cmd as follows.

caller.cmd
@echo off

setlocal

set VAR=Hello

endlocal

call callee.cmd
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:

×
Command Prompt Icon
Command Prompt
Microsoft Windows [Version xx.x.xxxxx.xxx]
(c) 2024 Ribbit App Development All rights reserved.
 
C:\users\user>caller.cmd
ECHO is <OFF>.

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.

Practice Question

Which of the following is the correct result displayed in the command prompt after executing the code below?

@echo off
set VAR=FirstValue

setlocal

set VAR=SecondValue

endlocal

echo %VAR%
#Command Prompt #Batch File #Arguments #Command Line #Commands