- Batch Script Tutorial
- Batch Script - Home
- Batch Script - Overview
- Batch Script - Environment
- Batch Script - Commands
- Batch Script - Files
- Batch Script - Syntax
- Batch Script - Variables
- Batch Script - Comments
- Batch Script - Strings
- Batch Script - Arrays
- Batch Script - Decision Making
- Batch Script - Operators
- Batch Script - DATE & TIME
- Batch Script - Input / Output
- Batch Script - Return Code
- Batch Script - Functions
- Batch Script - Process
- Batch Script - Aliases
- Batch Script - Devices
- Batch Script - Registry
- Batch Script - Network
- Batch Script - Printing
- Batch Script - Debugging
- Batch Script - Logging
- Batch Script Resources
- Batch Script - Quick Guide
- Batch Script - Useful Resources
- Batch Script - Discussion
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