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 working dir as the same folder from where the user called the .bat file.
But if the user terminates the batch processing before it is complete, the cmd show the current working dir (say "../asdf").
But in my case, I need to restore the working dir to the default/predefined one. Is it possible?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With