Simz
Simz

Reputation: 111

Checking existence of folders with/without spaces in names using IF statement in batch

I'm checking the existence of 2 folders using IF statement but when I do it with quotations for the variable "%X%", I get no answer although it works for "%Y%". The only difference between the 2 folders is the space in the name. Does this space play a role in this error and why!?

Thanks in advance!

SET X="C:\New Folder"
SET Y="C:\New_Folder"

C:\Users\Administrator>IF EXIST %X% (ECHO 1) ELSE (ECHO 0)
0

C:\Users\Administrator>IF EXIST "%X%" (ECHO 1) ELSE (ECHO 0)


C:\Users\Administrator>IF EXIST %Y% (ECHO 1) ELSE (ECHO 0)
0

C:\Users\Administrator>IF EXIST "%Y%" (ECHO 1) ELSE (ECHO 0)
0

Upvotes: 2

Views: 2080

Answers (1)

user7818749
user7818749

Reputation:

When you do set for directories with whitespace by adding the quotes to the path like:

SET X="C:\New Folder"

You are setting the variable to include the quotes. it will echo "C:\New Folder" when you type echo %x%

So by doing:

if exist "%X%" echo something

You are adding quotes, so you are checking existence of ""C:\New Folder""

Instead set like this:

SET "X=C:\New Folder"
SET "Y=C:\New_Folder"

Now if you do:

if exist "%X%" (echo 1) else (echo 2)

it will echo 1.

Upvotes: 3

Related Questions