user3076409
user3076409

Reputation: 23

Batch: how to check variables in the same batch with spaces in them

I would like to know if its possible to use spaces in variables in the same batch file and compare it with another variable even though they both have spaces in them.

Example:

@echo off
CLS
set var1=variable 1
set var2=variable 2
IF %var1%==%var2% (
goto matches
) else (
goto doesnt
)
:matches
echo.
echo  Both the Variables Match!
echo.
pause
exit
:doesnt
echo.
echo  Both the Variables DO NOT Match!
echo.
pause
exit

just adding that code as an example since a simple way of learning it i could use it as a reference to help me remember.

Showing me how to make the example above to work, would help me greatly if its possible to match variables while still containing its spaces. I know a good bit about Batch, just don't exactly know how to get spaces to work in variables in that way. Thanks for your time, hopefully there's a Solution.

Upvotes: 2

Views: 81

Answers (2)

dbenham
dbenham

Reputation: 130839

Enclosing the values in quotes, as per the malexander answer, will typically work. But it can fail if the value already contains quotes.

If you want to successfully compare values in variables no matter what the content, then you need delayed expansion:

setlocal enableDelayedExpansion
if !var! == !var2!

Upvotes: 3

malexander
malexander

Reputation: 4680

Put quotes around the variables.

IF "%var1%"=="%var2%"

Upvotes: 2

Related Questions