SETLOCAL

suggest change

When used in a batch file, makes all further changes to environment variables local to the current batch file. When used outside of a batch file, does nothing. Can be ended using ENDLOCAL. Exiting a batch file automatically calls "end local". Can be used to create subprograms: see Functions.

Furthermore, can be used to enable delayed expansion like this: "setlocal EnableDelayedExpansion". Delayed expansion consists in the names of variables enclosed in exclamation marks being replaced with their values only after the execution reaches the location of their use rather than at an earlier point.

The following is an example of using delayed expansion in a script that prints the specified number of first lines of a file, providing some of the function of the command "head" known from other operating systems:

@echo off

call :myhead 2 File.txt
exit /b

:: Function myhead
:: ===============
:: %1 - lines count, %2 - file name
:myhead
setlocal EnableDelayedExpansion
set counter=1
for /f "tokens=*" %%i in (%2) do ( 
  echo %%i
  set /a counter=!counter!+1
  if !counter! gtr %1 exit /b
)
exit /b

Links:

$ setlocal /?
Begins localization of environment changes in a batch file.  Environment
changes made after SETLOCAL has been issued are local to the batch file.
ENDLOCAL must be issued to restore the previous settings.  When the end
of a batch script is reached, an implied ENDLOCAL is executed for any
outstanding SETLOCAL commands issued by that batch script.

SETLOCAL

If Command Extensions are enabled SETLOCAL changes as follows:

SETLOCAL batch command now accepts optional arguments:
        ENABLEEXTENSIONS / DISABLEEXTENSIONS
            enable or disable command processor extensions. These
            arguments takes precedence over the CMD /E:ON or /E:OFF
            switches. See CMD /? for details.
        ENABLEDELAYEDEXPANSION / DISABLEDELAYEDEXPANSION
            enable or disable delayed environment variable
            expansion. These arguments takes precedence over the CMD
            /V:ON or /V:OFF switches. See CMD /? for details.
These modifications last until the matching ENDLOCAL command,
regardless of their setting prior to the SETLOCAL command.

The SETLOCAL command will set the ERRORLEVEL value if given
an argument.  It will be zero if one of the two valid arguments
is given and one otherwise.  You can use this in batch scripts
to determine if the extensions are available, using the following
technique:

    VERIFY OTHER 2>nul
    SETLOCAL ENABLEEXTENSIONS
    IF ERRORLEVEL 1 echo Unable to enable extensions

This works because on old versions of CMD.EXE, SETLOCAL does NOT
set the ERRORLEVEL value. The VERIFY command with a bad argument
initializes the ERRORLEVEL value to a non-zero value.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents