2

At the end of a batch file, I have this command:

 CD /D C:\

I want to change the directory to C:\ but the line doesn't do a thing.

This is what is on the screen:

 D:>CD /D C:\
 D:>

At this moment, if I enter manually "CD /D C:\", I can change directory to C:.

What should I do to make it work?

joehua
  • 725
  • 3
  • 10
  • 25
  • 3
    Most likely because you are using setlocal in your script. – Squashman Sep 12 '16 at 15:29
  • 1
    The problem is that your batch file has _its own_ current directory. When you do `CD` inside, it doesn't affect the current directory outside. And if one batch file calls another, they all have their own. – MSalters Sep 12 '16 at 15:29
  • 2
    @MSalters Only if `setlocal` has been used. Unlike *nix scripts, batch scripts don't have their own environment by default. – TripeHound Sep 12 '16 at 15:36
  • @TripeHound: Correct, `setlocal` is the root cause. I just explained the direct cause (non-shared environment) which is why my comment is not an answer.. – MSalters Sep 12 '16 at 15:38
  • Thanks. You are correct. It works after I add "endlocal" before the line. – joehua Sep 12 '16 at 15:49

2 Answers2

3

you probably have a setlocal in your batch script. The following should work:

... your batchfile
endlocal
cd /d c:\
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • For completeness, if you wanted to change to a directory held in a (local) environment variable, you could do `endlocal && cd/d %TARGETDIR%` (see [this question and its answers](http://stackoverflow.com/q/3262287/2096401)). – TripeHound Sep 12 '16 at 15:41
  • @TripeHound: a single `&` [should do](http://ss64.com/nt/syntax-redirection.html) – Stephan Sep 12 '16 at 15:47
  • True. Probably force of habit from *nix days when a single `&` would run in parallel. – TripeHound Sep 12 '16 at 16:06
0

There is an easier way of doing this, if you are in the D:/ drive, and you want to switch to the C:/ drive, you can just type the drive letter that you want to switch to followed by a colon for example you are in the C:/ drive and want to switch to the D:/ drive, type just D: on a line, it will then switch the current drive.

  • 1
    This isn't an answer to this question, as the problem was that `cd /D C:\ ` doesn't work at all, so your tip would fail, too. Btw. `C:` is different to `cd /D C:\ ` as the second will switch the drive **and** set the path – jeb Sep 13 '16 at 07:19