why is my cd %myVar

前端 未结 2 356
北恋
北恋 2020-11-30 15:31

I save my original path in originalPath and then move to another folder. At the end when I do cd %originalPath%, it doesn\'t work. It stays in the

2条回答
  •  死守一世寂寞
    2020-11-30 16:29

    Actually it does not really stay in the changed directory. The real problem is that setlocal, besides environment variable changes, caches the current directory, which you already changed by cd %myPath%.

    Then you switch back to the former directory by cd %originalPath%. But as soon as the batch script finishes execution, an implicit endlocal occurs which resets the current directory to the one previously cached by setlocal.

    The issue is exactly the same if you remove REM from the pushd and popd lines and comment out the cd lines instead.

    To solve the problem, simply move the cd %myPath% line (or the pushd command) down below setlocal. Actually you do even not need to store the current directory initially when you change it only in between the setlocal/endlocal block (even if endlocal is not explicitly stated):

    @echo off
    set myPath=Subfolder1
    set folderList=input.txt
    
    setlocal EnableDelayedExpansion
    REM pushd %myPath%
    cd %myPath%
    
    :process
    
    REM The rest of my script
    
    REM popd
    pause
    endlocal
    

提交回复
热议问题