1

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?

2
  • 1
    What error are you getting when doing this? You should be able to have spaces in the basepath path and then concatenate the rest on. Commented Apr 23, 2014 at 19:46
  • I was using double quotes incorrectly, like set basepath="c:\some\path" and concatenating to that. The error I was getting was "filename, directory name, or volume label syntax is incorrect". As MC ND and Rob K answered below, I should just double quote the final command, which works great Commented Apr 23, 2014 at 20:02

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Not really. If there are spaces at the end of the set command assigned value, they are included in the value of the variable.
You are correct. I was thinking it trimmed it. I will edit my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.