如何在批处理文件中正确使用CD命令?

3
我是新手批处理脚本编写者,只是尝试编写一个简单的批处理文件,可以直接进入我经常使用的目录,而无需每次都执行cd命令。
@ECHO OFF
CD /
CD D:
CD programming/

当我保存并尝试运行它时,它会出现错误:

the system cannot find the file specified path 

尽管在提示符上直接运行这些命令没有问题,但仍需要注意。

使用反斜杠将有所帮助。 - undefined
1
这个回答解决了你的问题吗?使用变量在批处理文件中更改目录 - undefined
一句话回答:cd D:/programming/ - undefined
2
cd命令在不加上/d开关的情况下无法切换驱动器。你只需要一行代码:cd /d D:\programming。请注意,我使用的是反斜杠而不是正斜杠。 - undefined
顺便说一句:在99.9999999%的情况下,Windows和DOS标签是没有意义的。 - undefined
2个回答

5

首先,Windows路径分隔符是\而不是/

然后你需要了解每个驱动器都有一个当前目录,才能完全理解发生了什么。

无论如何,这里是一份经过适应的代码版本,并附带一些说明:

rem /* This changes to the root directory of the drive you are working on (say `C:`);
rem    note that I replaced `/` by `\`, which is the correct path separator: */
cd \
rem /* This changes the current directory of drive `D:` to the current directory of drive `D:`,
rem    note that this does NOT switch to the specified drive as there is no `/D` option: */
cd D:
rem /* This is actually the same as `cd programming` and changes to the sub-directory
rem    `programming` of your current working directory: */
cd programming\
rem /* The final working directory is now `C:\programming`, assuming that the original
rem    working drive was `C:`. */

然而,我认为你想要实现的是以下内容:
rem // This switches to the drive `D:`; regard that there is NO `cd` command:
D:
rem // This changes to the root directory of the drive you are working on, which is `D:`:
cd \
rem // This changes into the directory `programming`:
cd programming
rem // The final working directory is now `D:\programming`.

这可以简化为:
D:
cd \programming

甚至是这个:

rem // Note the `/D` option that is required to also switch to the given drive:
cd /D D:\programming

实际上我犯了一个愚蠢的错误,我写成了cd D:而不是D:,现在我明白了。 - undefined

0

当你使用

cd d:

D: 的当前目录可能不是 D:\

要设置根目录,你需要使用 CD D:\

在 Windows 中,请使用反斜杠


嗯,虽然你说的是对的(因为每个驱动器都有自己的当前目录),但是如果你不添加/D选项,它并不会切换到D:驱动器。 - undefined
我之前说的是,如果D:驱动器之前设置为根目录之外的其他目录,比如D:\ work,当您使用CD D:时,它会返回到D:中的先前目录,也就是D:\ work,那里没有一个名为“programming”的目录。 - undefined
你是对的,cd D:\会改变当前工作目录到D:驱动器(不管你当前在哪个驱动器上工作);cd D:是无用的,因为它只会将当前工作目录更改为驱动器:D的当前目录。无论如何,我想说的是:当你在C:驱动器上工作时,你可以输入cd D:或者cd D:\,但你仍然会停留在C:驱动器上,除非你使用cd /D而不是cd,这样你就会同时改变驱动器。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接