I am trying to use setlocal enabledelayedexpansion
and cd
together in a batch script, which seems to not persist changes back to shell.
The reason I need setlocal enabledelayedexpansion
is that I need the variables in the script to be expanded dynamically upon runtime of the script.
Consider the below sample batch file :
a.bat
================================
setlocal enabledelayedexpansion
cd ..
The above batch file does not migrate to previous directory as expected !
Check this.
Blorgbeard provided an explanation as to why CD issued after SETLOCAL does not persist after ENDLOCAL (could be explicit or implicit).
Here is an interesting work-around. The PUSHD stack is independent of the environment that is saved/restored by SETLOCAL/ENDLOCAL. So the following simple sequence will preserve the directory change:
Not very useful if
somePath
is constant - you could just as easily issue the CD after the ENDLOCAL. But it can be very useful ifsomePath
is dynamic.Here is proof that it works - start the batch file in any folder above the root.
The problem is that
setlocal
causes any current directory changes to be local to the batch file.See
setlocal /?
:Current directory is included in "environment changes".
Try this, notice that it echoes
C:\
for%CD%
inside the batch, but the current directory is still reset when the batch exits.Saving a string in registry across endlocal. Tested on win7 cmd (skip=2, may differ with different versions of reg.exe)
Edit Stephan another way to save variables beyond
endlocal
:The trick is that due to the parsing the variables are expanded before
endlocal
is effective, butset
ted after that.(sorry for hijacking your answer, but that's also too big for a comment)