Restore default working dir if bat file is terminated abruptly
Asked Answered
S

1

12

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?

  • Batch file is written by me, so I can modify it.
  • CMD is opened through a desktop shortcut to CMD, which I have control of; so properties like working dir or passing args to CMD etc can be done there.
Selfcommand answered 27/3, 2013 at 10:43 Comment(1)
If the user terminates the batch, the batch can't restore the default folder.Nonpros
T
31

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.

Tadeas answered 27/3, 2013 at 12:53 Comment(3)
+1. I thought at first that you are wrong, but it works! setlocal store the current directory and endlocal return to it, even with several nested setlocal/endlocal pairs! This behavior is undocumented (tested in Win-XP). Where did you know about it?Acquisitive
@Acquisitive - Just from my own observations. I didn't think about nesting setlocals, but I guess it makes sense that runtime environments can be nested that way.Tadeas
@AndriyM - Ah, sorry. I've got gnuwin32 installed on my work computer, cygwin on one of my home computers, and I'm back and forth between Linux and Windows so often that I sometimes forget which commands are native to which OS. :> I'll fix it. pwd is Linux-ese for print working directory, and does the same thing as cd with no arguments or echo %cd% in Windows.Tadeas

© 2022 - 2024 — McMap. All rights reserved.