Restore default working dir if bat file is terminated abruptly

后端 未结 1 1627
傲寒
傲寒 2020-12-06 17:23

I have a scenario where during execution of a batch file, it navigates to a different folder (say to \"../asdf\"); and at the end of execution it will set the current workin

1条回答
  •  借酒劲吻你
    2020-12-06 18:22

    In your batch script use setlocal to encapsulate the running environment of your batch session. If the user terminates the script before you cd or popd to return, your script will still exit in the directory in which it started. Here's a brief test:

    @echo off
    setlocal
    pushd c:\Users
    cd
    exit /b
    

    Output:

    C:\Users\me\Desktop>test.bat
    c:\Users
    
    C:\Users\me\Desktop>
    

    Notice I didn't popd or cd %userprofile%\Desktop, but I still ended up back at my Desktop after the script exited.

    Additionally, setlocal keeps you from junking up your environment with orphaned variables that mean nothing outside of your batch script. It's just good practice. At the console, type help setlocal for more info.

    0 讨论(0)
提交回复
热议问题