If branching doesn't work

Microsoft Windows
Post Reply
User avatar
MigrationUser
Posts: 336
Joined: 2021-Jul-12, 1:37 pm
Contact:

If branching doesn't work

Post by MigrationUser »

12 Nov 2019 03:12
Shane


Greetings,

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

Code: Select all

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

----------------------------

#2 12 Nov 2019 13:30
bluesxman


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

Code: Select all

if %_var%=="test" echo %_var% is defined
You need to "protect" your variable with quotes:

Code: Select all

if "%_var%"=="test" echo %_var% is defined
cmd | *sh | ruby | chef

----------------------------

#3 12 Nov 2019 19:45
Shane


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

----------------------------

#4 12 Nov 2019 21:17
Simon Sheppard


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.

----------------------------

#5 12 Nov 2019 21:24
Simon Sheppard
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

Code: Select all

set /a "_var+=0"
Post Reply