Any reason to split up “cd” commands in Windows?

2019-07-19 15:04发布

问题:

I'm cleaning up some old Windows batch files at work, and keep seeing lines like this:

D:
cd\
cd some\other\path\

is there any reason (compatibility with command.com maybe?) to not just write this as

cd /d d:\some\other\path\

回答1:

cd doesn't actually change the working drive; it only changes the working directory for that drive. That's why it's broken up that way.

An example might help:

C:\users\david>cd D:\some\path
C:\users\david>

Note the drive hasn't changed.

C:\users\david>D:
D:\some\path>

Now that D: is the "working disk", the working directory is changed to what you specified previously.

As you point out, cd /d will do both. [UPDATE: I must have missed the /d when reading your original post :( -- sorry]

I believe you're correct -- there's no "good" reason not to use the one-liner -- other than compatibility with COMMAND.COM (which I'm pretty sure doesn't support the /d switch). For this reason, I always create my script files with a .cmd extension if they depend on features not supported in COMMAND.COM.

A better alternative IMHO is to use pushd which behaves like cd /d -- and also gives you the ability to go back to wherever you were before (via popd). You can even pushd to a UNC path (\\server\share) and Windows will create a temporary drive letter for you. (Although I only found that feature this morning, and I'm running Win 7 Pro, so I'm not sure if it's available on older versions and/or Home editions.)