Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SETLOCAL ENABLEDELAYEDEXPANSION causes CD and PUSHD to not persist

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.

like image 910
Raghav RV Avatar asked Oct 07 '14 22:10

Raghav RV


2 Answers

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:

@echo off
setlocal
cd somePath
pushd .
endlocal
popd

Not very useful if somePath is constant - you could just as easily issue the CD after the ENDLOCAL. But it can be very useful if somePath is dynamic.

like image 98
dbenham Avatar answered Nov 15 '22 03:11

dbenham


The problem is that setlocal causes any current directory changes to be local to the batch file.

See 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.

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.

[11:42:00.17] C:\temp
> cat test.bat
@echo off
setlocal enabledelayedexpansion
cd ..
echo %CD%
[11:42:19.38] C:\temp
> test.bat
C:\

[11:42:23.00] C:\temp
>
like image 32
Blorgbeard Avatar answered Nov 15 '22 03:11

Blorgbeard