user3683832
user3683832

Reputation: 149

Batch - Search if a variable contains spaces

I have a variable that I need to check if it contains spaces, and exit if it does. I have this code:

if not [%VAR%]==[%VAR: =%] exit 1

.. but it does not work for spaces. I can use it for other characters though. For example looking for "/" works with same code:

if not [%VAR%]==[%VAR:/=%] exit 1

Is there a way to do it?

Thanks,

Upvotes: 6

Views: 8281

Answers (2)

MC ND
MC ND

Reputation: 70923

While the answer from foxidrive will handle the problem for simple cases and is the obvious answer (and yes, this is what i usually use), it will fail for values with a quote inside

"If needed" this should handle the marginal cases

for /f "tokens=2 delims= " %%a in (".%var:"=%.") do exit 1

The "trick" is to enclose the value with removed quotes and tokenize the string using for command. To avoid spaces at the start and end of the string from being removed a pair of aditional dots are included. If the string do not include a space, it will only have one token. But the for command is requesting the second token, so the code inside will not be executed for strings without a space in them.

Upvotes: 4

foxidrive
foxidrive

Reputation: 41234

This should do as you need: double quotes are always the solution for spaces, and also with some other characters.

if not "%VAR%"=="%VAR: =%" exit 1

Upvotes: 9

Related Questions