51

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Louis Rhys
  • 34,517
  • 56
  • 153
  • 221

3 Answers3

78

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

Prog1.exe
Pushd D:\SomeDir
Prog2.exe
popd
Prog3.exe
jeb
  • 78,592
  • 17
  • 171
  • 225
13

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.

72er
  • 5
  • 3
David Ruhmann
  • 11,064
  • 4
  • 37
  • 47
13

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.

Community
  • 1
  • 1
Ryan
  • 22,332
  • 31
  • 176
  • 357
  • 3
    what does /d mean? – Maksym Semenykhin Nov 09 '16 at 05:50
  • 5
    @СеменихинМаксим, From the documentation: "Use the /D switch to change current drive in addition to changing current directory for a drive." Basically, you always want to specify it when changing dir to arbitrary absolute paths. – Mikhail Dec 31 '16 at 12:23