#1 12 Nov 2019 03:12

Shane
Member
From: Victoria, BC
Registered: 17 May 2018
Posts: 7

if branching doesn't work

Greetings,

I'm trying to use IF DEFINED  to control branching, but it doesn't work. I will start with an example

setLocal
if defined _var (
::	_var is NOT defined, so the next line should not be executed
	if %_var%=="test" echo %_var% is defined
)
endLocal

Processing stops when it hits the ECHO statement and exits with "echo was unexpected at this time." error message.

The problem is that the nested IF statement is being executed, and it shouldn't be because _var is not defined. How can I fix this?

Thanks,
Shane.

Last edited by Shane (12 Nov 2019 03:15)


Windows 10 Home 64-bit

Offline

#2 12 Nov 2019 13:30

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,101

Re: if branching doesn't work

If %_var% is undefined, I think you'll be creating a syntax error on this line:

if %_var%=="test" echo %_var% is defined

You need to "protect" your variable with quotes:

if "%_var%"=="test" echo %_var% is defined

cmd | *sh | Ruby | Chef

Offline

#3 12 Nov 2019 19:45

Shane
Member
From: Victoria, BC
Registered: 17 May 2018
Posts: 7

Re: if branching doesn't work

Thanks for your reply.

The nested IF shouldn't be producing a syntax error, because the first IF condition is false: meaning that everything in the parenthesis should not be evaluated.

There are other instances when the variable would be defined, however, the variable would be set using the arithmetic argument:

set /a "var=1"

How can I 'protect' a variable if it is not a string?

Thanks,
Shane.

Last edited by Shane (12 Nov 2019 19:54)


Windows 10 Home 64-bit

Offline

#4 12 Nov 2019 21:17

Simon Sheppard
Super Administrator
Registered: 27 Aug 2005
Posts: 1,039
Website

Re: if branching doesn't work

Whats happening here is that the error is being thrown when the command is being parsed. The way you have written the IF DEFINED followed by a code block in brackets, everything inside the brackets gets parsed as though it is on the same line, so even if parts of it should never be executed in practise, it is still enough to make your script throw an error.

One workaround would be to do something like
IF NOT DEFINED _var Goto Skip
(code block)
:Skip

but I much prefer bluesxman's solution of just testing the variable once, but protecting it with quotes so that it works reliably.

Offline

#5 12 Nov 2019 21:24

Simon Sheppard
Super Administrator
Registered: 27 Aug 2005
Posts: 1,039
Website

Re: if branching doesn't work

Shane wrote:

How can I 'protect' a variable if it is not a string?

== will always do a string comparison, so use EQU for numeric comparisons.

To force it to always be defined, you can just add zero, assuming that makes sense for your application

set /a "_var+=0"

Offline

Board footer

Powered by FluxBB