Restore default working dir if bat file is terminated abruptly

为君一笑 提交于 2019-11-28 00:56:30

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!