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

Aqu*_*ikh 3 windows cmd batch-file

我是批处理脚本的新手,只是想编写一个简单的批处理文件,该文件将转到我经常使用的目录,而不必每次都执行 cd 。

@ECHO OFF
CD /
CD D:
CD programming/
Run Code Online (Sandbox Code Playgroud)

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

the system cannot find the file specified path 
Run Code Online (Sandbox Code Playgroud)

即使这些命令在直接按提示执行时运行良好

asc*_*pfl 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:`. */
Run Code Online (Sandbox Code Playgroud)

但是,我认为您想要实现的目标如下:

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`.
Run Code Online (Sandbox Code Playgroud)

这可以缩短为:

D:
cd \programming
Run Code Online (Sandbox Code Playgroud)

甚至是这个:

rem // Note the `/D` option that is required to also switch to the given drive:
cd /D D:\programming
Run Code Online (Sandbox Code Playgroud)