How to set the working directory of a command in a Windows batch file?

本秂侑毒 提交于 2019-12-18 12:05:05

问题


Let's say I have these commands:

Prog1.exe
D:\SomeDir\Prog2.exe
Prog3.exe

Now, say for the second line, I would like the working directory to be D:\SomeDir, but in Prog1.exe and Prog3.exe I want the default working directory (normally, where my .bat file is). If I try this

Prog1.exe
cd D:\SomeDir
D:\SomeDir\Prog2.exe
Prog3.exe

Apparently Prog3 will be executed in SomeDir, which is not what I want.


回答1:


You could use the pushd/popd commands (help with pushd /?)

Prog1.exe
Pushd D:\SomeDir
Prog2.exe
popd
Prog3.exe



回答2:


You could use the cd command (help with cd /?) with the %~dp0, batch file path, variable.

Prog1.exe
cd D:\SomeDir
Prog2.exe
cd %~dp0
Prog3.exe

For a complete list of %~ modifiers see call /? or for /? help.

However, I only add this as to provide a more complete answer on Stack Overflow. I would RECOMMEND using jeb's solution above.




回答3:


What worked for me is adding a /d:

cd /d C:\nginx
ECHO Stopping nginx...
start nginx -s quit

(When I didn't have the /d, it didn't work.)

https://stackoverflow.com/a/18310141/470749 tries to explain it.



来源:https://stackoverflow.com/questions/9597001/how-to-set-the-working-directory-of-a-command-in-a-windows-batch-file

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