Skip to main content

Batch Script Local Variables in Functions

Local Variables in Functions

Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function.

How it works

  • The SETLOCAL command is used first to ensure that the command processor performs a backup of all environment variables.
  • Variables can be restored by calling the ENDLOCAL command. Changes made in the interim are local to the current batch script.
  • ENDLOCAL is called automatically when the end of the batch file is reached, that is, when GOTO:EOF is called.
  • Localizing variables with SETLOCAL allows free use of variable names within a function, without worrying about name conflicts with variables used outside the function.

Example

The following example shows how local variables can be used in functions.

Example of Local Variables in Function
@echo off
set str = Outer
echo %str%
CALL :SetValue str
echo %str%
EXIT /B %ERRORLEVEL%

:SetValue
SETLOCAL
set str = Inner
set "%~1 = %str%"
ENDLOCAL
EXIT /B 0
Outer
Outer

Note that in the above program the variable str is being localized in the function SetValue. Thus even though the str value is being returned back to the main function, the value of str in the main function will not be replaced by the value being returned from the function.