Skip navigation

JSI Tip 0970. SETLOCAL and ENDLOCAL in a batch script.

The SETLOCAL command in a batch file, begins localization of the environment variables. SETLOCAL makes an image of the environment variables and ENDLOCAL restores that image.

You can have up to 32 levels of localization:

...
setlocal
set username=Jerry
call :levela
enlocal
goto end
:levela
setlocal
set username=jennifer
....
endlocal
:end

Using the SETLOCAL and ENDLOCAL commands in tip 964, JSILLD.bat can be reduced from 100 statements to 88 statements. Here is the part of the script that is changed:

 Revised   Previous 
 @echo off   @echo off 
 setlocal    
 if "%1"

"" goto syntax

 
 if "%1""" goto syntax 
 if "%2"

"" goto syntax

 
 if "%2""" goto syntax 
 if "%3"

"" goto begin

 
 if "%3""" goto begin 
 if /i "%3"

"/n" goto begin

 
 if /i "%3""/n" goto begin 
 :syntax   :syntax 
 @echo Syntax: JSILLD File yyyymmdd \[/N\]   @echo Syntax: JSILLD File yyyymmdd \[/N\] 
 endlocal   set dte= 
    set XX= 
 goto end   goto end 
 :begin   :begin 
 if /i "%2"

"/n" goto syntax

 
 if /i "%2""/n" goto syntax 
 set dte=%2   set dte=%2 
 set XX=%dte:~0,4%   set XX=%dte:~0,4% 
 if "%XX%" LSS "1993" goto syntax   if "%XX%" LSS "1993" goto syntax 
 set XX=%dte:~4,2%   set XX=%dte:~4,2% 
 if "%XX%" LSS "01" goto syntax   if "%XX%" LSS "01" goto syntax 
 if "%XX%" GTR "12" goto syntax   if "%XX%" GTR "12" goto syntax 
 set XX=%dte:~6,2%   set XX=%dte:~6,2% 
 if "%XX%" LSS "01" goto syntax   if "%XX%" LSS "01" goto syntax 
 if "%XX%" GTR "31" goto syntax   if "%XX%" GTR "31" goto syntax 
 set never=%3   set never=%3 
 set file=%1   set file=%1 
 if exist %file% del /q %file%   if exist %file% del /q %file% 
 for /f "Skip=4 Tokens=*" %%i in ('net users') do call :parse "%%i"   for /f "Skip=4 Tokens=*" %%i in ('net users') do call :parse "%%i" 
 endlocal   set str= 
    set substr= 
    set ustr= 
    set txt= 
    set fullname= 
    set never= 
    set file= 
    set dte= 
    set XX= 
    set YY= 
    set MM= 
    set DD= 
    set YMD= 
 goto end   goto end 

You can use a little trick to have SETLOCAL and ENDLOCAL in a batch and still return environment variables. Assume a script contains:

@echo off
setlocal
...
set /a tmp1=1
set /a tmp2=2
set /a tmp3=3
...
set /a var1=%tmp1% + %tmp3%
...
set /a var2=%tmp2% * %var1%
...
endlocal
:end

Because the shell evaluates environments variables in a command before executing it, you could return var1 and var2 by changing the endlocal (above) to:

endlocal & set /a var1=%var1% & set /a var2=%var2%

The shell interprets this as:

endlocal & set /a var1=4 & set /a var2=8

before executiion.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish