Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch - Search if a variable contains spaces

Tags:

batch-file

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,

like image 852
user3683832 Avatar asked Jul 08 '14 15:07

user3683832


2 Answers

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
like image 142
foxidrive Avatar answered Oct 18 '22 01:10

foxidrive


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.

like image 40
MC ND Avatar answered Oct 18 '22 01:10

MC ND