SETLOCAL ENABLEDELAYEDEXPANSION causes CD and PUSHD to not persist

前端 未结 4 443
春和景丽
春和景丽 2021-01-18 08:41

I am trying to use setlocal enabledelayedexpansion and cd together in a batch script, which seems to not persist changes back to shell.

The

4条回答
  •  迷失自我
    2021-01-18 08:58

    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.

提交回复
热议问题