Bersch02
Bersch02

Reputation: 9

How to use an IF ELSE command

I am a beginning coder creating a text-based game on batch and I am wondering how to say the following in code:

If {these variables} have been defined 
Then goto {this loop} 
Else goto {other loop}

If anyone has a link to a tutorial or can answer in a stack answer that would be awesome! Thanks!

Upvotes: 0

Views: 252

Answers (2)

user6811411
user6811411

Reputation:

Put that into a loop breaking if just one var isn't defined

For %%A in (these variables) Do If not defined %%A goto :otherloop
Echo all vars defined
Goto :eof

:otherloop 
Echo not all vars defined

Upvotes: 2

Squashman
Squashman

Reputation: 14340

This is just one way you could test to see if all variables you need are defined. You can use a FOR command to loop through all the variable names and use an IF command to see if they are defined. I then set two counters. One for the total number of variables and one for the total number of variables that are defined.

@echo off

REM Change these variables to test logic
set "var1=one"
set "var2=two"
set "var3=3"

set "allvars=var1 var2 var3"

set "vcnt=0"
set "defcnt=0"
FOR %%G IN (%allvars%) do (
    set /a vcnt+=1
    IF DEFINED %%G SET /a defcnt+=1
)

IF %vcnt% equ %defcnt% (
    GOTO allvars
) else (
    GOTO notdefined
)

:allvars
echo All variables defined
GOTO END

:notdefined
echo Some variables not defined
GOTO END

:END
pause

Upvotes: 2

Related Questions