s_om
s_om

Reputation: 681

If statement variable assignment in batch file ignored

I am new to batch file coding and am trying to write a simple If-Else statement.

I have tried to use delayedexpansion as suggested in other questions but still don't seem to get the right value

@echo off
setlocal ENABLEDELAYEDEXPANSION

SET VAR=portrait
IF %VAR% == portrait do (
    SET /a height=1920;
    set /a width=1080;
) else do(
    set /a height=1080;
    set /a width=1920;
)

echo %height%

The code above gives the output as 1080, while I am expecting 1920 based on the logic I wrote. Can someone please help me understand?

Upvotes: 0

Views: 137

Answers (1)

Compo
Compo

Reputation: 38589

You issue is mainly because there's no such thing as an If / Do or Else / Do statement. Also you should try to remember that Set /A is really for arithmetic, and you're not doing math, just setting values to names.

If "%VAR%" == "portrait" (
    Set "height=1920"
    Set "width=1080"
) Else (
    Set "height=1080"
    Set "width=1920"
)
Echo %height%

However, you can in this case, still use Set /A to shorten your commands a little; because Set /A allows for multiple names to integer values within the same statement.

If "%VAR%" == "portrait" (
   Set /A height=1920, width=1080
) Else (
   Set /A height=1080, width=1920
)
Echo %height%

Upvotes: 2

Related Questions