SETLOCAL ENABLEDELAYEDEXPANSION causes CD and PUSHD to not persist

前端 未结 4 574
春和景丽
春和景丽 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:49

    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
    >
    

提交回复
热议问题