Batch Script - Local Variables in Functions



Local variables in functions can be used to avoid name conflicts and keep variable changes local to the function. The SETLOCAL command is first used to ensure the command processor takes a backup of all environment variables. The variables can be restored by calling ENDLOCAL command. Changes made in between are local to the current batch script. ENDLOCAL is automatically called when the end of the batch file is reached, i.e. by calling GOTO:EOF.

Localizing variables with SETLOCAL allows using variable names within a function freely without worrying about name conflicts with variables used outside the function.

Following example shows how local variables can be used in functions.

Example

@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

Output

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.

The above command produces the following output.

Outer
Outer
batch_script_functions.htm
Advertisements