Restore default working dir if bat file is terminated abruptly Restore default working dir if bat file is terminated abruptly shell shell

Restore default working dir if bat file is terminated abruptly


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 offsetlocalpushd c:\Userscdexit /b

Output:

C:\Users\me\Desktop>test.batc:\UsersC:\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.