批处理脚本中带有空格的路径名

问题描述:

我在批处理脚本中的目录名称中存在空格问题.

I have a problem with spaces in directory names in a batch script.

我存储一个基本目录,然后用它来创建子目录和文件,例如:

I store a base directory and then use that to make subdirectories and files, something like:

set basepath=c:\some\path
set logdir=%basepath%\log
set logfile=%logdir%\test.log

但是某些服务器上的基本路径中有空格.早些时候,我使用dir /x来获得8.3的缩写,但是我遇到了一台服务器,该服务器不起作用(显然有一些设置可以禁用它,并且我没有特权将其重新打开).所以现在我想弄清楚这一点.我需要将文件名/目录连接到基本路径,其中可能有空格.我尝试使用双引号,但是没有用.

But the basepath on some servers have spaces in it. Earlier I used dir /x to get the shortened 8.3 names but I encountered one server where this doesn't work (apparently there is some setting to disable this, and I don't have privileges to turn it back on). So now I'm trying to figure this out. I need to concatenate filename/directories to basepath, which may have spaces in it. I tried using double quotes, but it didn't work.

在命令提示符下,可以使用双引号目录和非双引号目录的组合来执行cd "some path"\with\spaces之类的操作.但这在批处理脚本中不起作用.

At the command prompt, you can do things like cd "some path"\with\spaces using a combination of double quoted directories and non-double-quoted directories. But this doesn't work in a batch script.

有什么建议吗?

仅在需要实际使用环境变量时,才将双引号引起来.

Put double quotes around the environment variable only when you need to actually use it.

set basepath=c:\some\path with spaces
set logdir=%basepath%\log

xcopy *.log "%logdir%" 

然后将其引用为"%logdir%",它将扩展为"c:\some\path with spaces\log".之所以有效,是因为set所有内容放在= 之后,除了 包括的尾随空格都放入环境变量中.

Then reference it as "%logdir%" and it will expand to "c:\some\path with spaces\log". This works because set puts everything after the = except for including trailing white-space into the environment variable.