zako42
zako42

Reputation: 664

pathnames with spaces in batch script

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

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.

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.

Any suggestions?

Upvotes: 1

Views: 8774

Answers (2)

Rob K
Rob K

Reputation: 8926

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%" 

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.

Upvotes: 1

MC ND
MC ND

Reputation: 70941

set "basePath=c:\somewhere\over the rainbow"
set "logDir=%basePath%\logs"
set "logFile=%logDir%\kansas.log"

>> "%logFile%" echo This is a test
cd "%logDir%"

Don't insert quotes inside the variable values (unless it is necessary).

Use quotes surounding the set command to ensure no aditional spaces are stored in variables and to protect special characters.

Place quotes in the correct places in the final commands that make use of the variables.

Upvotes: 2

Related Questions