Doctor Who
Doctor Who

Reputation: 1659

setting multiple variables in if statement using batch script

I have a batch script where I need to set multiple variables when a user enters a number. For some reason the country isn't getting set. What am I doing wrong?

set /P CLIENTOPTION=CLIENT:
IF /I '%CLIENTOPTION%'=='1' set CLIENTCHOICE=y set COUNTRY=UK
IF /I '%CLIENTOPTION%'=='2' set CLIENTCHOICE=w set COUNTRY=UK
IF /I '%CLIENTOPTION%'=='3' set CLIENTCHOICE=x set COUNTRY=UK
IF /I '%CLIENTOPTION%'=='4' set CLIENTCHOICE=y set COUNTRY=USA
IF /I '%CLIENTOPTION%'=='5' set CLIENTCHOICE=z set COUNTRY=CANADA

Upvotes: 5

Views: 11968

Answers (2)

foxidrive
foxidrive

Reputation: 41234

This could be made more robust but all you are missing is the & command separator.

set /P CLIENTOPTION=CLIENT:
IF /I '%CLIENTOPTION%'=='1' set CLIENTCHOICE=y&set COUNTRY=UK
IF /I '%CLIENTOPTION%'=='2' set CLIENTCHOICE=w&set COUNTRY=UK
IF /I '%CLIENTOPTION%'=='3' set CLIENTCHOICE=x&set COUNTRY=UK
IF /I '%CLIENTOPTION%'=='4' set CLIENTCHOICE=y&set COUNTRY=USA
IF /I '%CLIENTOPTION%'=='5' set CLIENTCHOICE=z&set COUNTRY=CANADA

Upvotes: 8

David
David

Reputation: 6571

The assignment uses everything on the same line after =. For example, for CLIENTOPTIONS === 1, the variable CLIENTCHOICE is being assigned everything after =, which is the string "y set COUNTRY=UK". Obviously, not what you intended.

You can get around this, and get the expected behavior, by using parentheses, and placing each action on a separate line, like so:

set /P CLIENTOPTION=CLIENT:
IF /I '%CLIENTOPTION%'=='1' ( 
    set CLIENTCHOICE=y
    set COUNTRY=UK
)
IF /I '%CLIENTOPTION%'=='2' ( 
    set CLIENTCHOICE=w 
    set COUNTRY=UK
)
IF /I '%CLIENTOPTION%'=='3' ( 
    set CLIENTCHOICE=x 
    set COUNTRY=UK
)
IF /I '%CLIENTOPTION%'=='4' ( 
    set CLIENTCHOICE=y 
    set COUNTRY=USA
)
IF /I '%CLIENTOPTION%'=='5' (
    set CLIENTCHOICE=z 
    set COUNTRY=CANADA
)

Upvotes: 3

Related Questions