views:

69

answers:

4

I need to test if a variable is set or not. I've tried several techniques but they seem to fail whenever %1 is surrounded by quotes such as the case when %1 = "c:\some path with spaces".

IF NOT %1 GOTO MyLabel // This is invalid syntax
IF "%1" == "" GOTO MyLabel // Works unless %1 has double quotes which fatally kills bat execution
IF %1 == GOTO MyLabel // Gives an unexpected GOTO error.

According to this site. These are the support IF syntax types. So, I don't see a way to do it.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
+4  A: 

Use parentheses instead of quotes:

IF (%1) == () GOTO MyLabel
Dan Story
A: 

I usually use this:

IF "%1."=="." GOTO MyLabel

If %1 is empty, the IF will compare "." to "." which will evaluate to true.

aphoria
This is incorrect. This is the same thing as: IF "%1" == "" the reason for this post was if %1 itself has quotes this fails.
blak3r
Are you trying to test if %1 is empty or if it has quotes? The question is unclear. My answer works if nothing is specified on the command line for %1.
aphoria
+1  A: 

You can use:

IF "%~1" == "" GOTO MyLabel

to strip the outer set of quotes.

jamesdlin
+1 I haven't tried that. But, that is GREAT to know.
blak3r
A: 

From IF /?:

If Command Extensions are enabled IF changes as follows:

IF [/I] string1 compare-op string2 command
IF CMDEXTVERSION number command
IF DEFINED variable command

......

The DEFINED conditional works just like EXISTS except it takes an environment variable name and returns true if the environment variable is defined.

Andy Morris
Yes, I actually tried this approach and from what I could tell this only works with ENVIRONMENT variables. Therefore, didn't work with %1 or a variable defined inside the batch file.
blak3r