Kwehmann
Kwehmann

Reputation: 19

Nested IF Statement, unexpected error

I have created a nested if statement that just performs very simple tasks. Here is the code below:

@ECHO OFF
SET ANS=%1
IF "%ANS%"=="" ( ECHO You Entered Nothing
  )
  IF /i %ANS%==Y ( ECHO You entered Yes
    )
    IF /i %ANS%==N ( ECHO You entered NO
      )
      IF %ANS%==? ( ECHO I am confused
        )

My problem is that when "%ANS%"=="" i get a "( was unexpected at this time" after echoing the message i have provided. Everything else works as planned but i am not sure why i am getting this message.

Upvotes: 0

Views: 423

Answers (3)

foxidrive
foxidrive

Reputation: 41234

This has elements that protect it from spaces and duoble quotes and & characters.

@ECHO OFF
SET "ANS=%~1"
IF "%ANS%"==""     ( ECHO You Entered Nothing  )
IF /i "%ANS%"=="Y" ( ECHO You entered Yes      )
IF /i "%ANS%"=="N" ( ECHO You entered NO       )
IF "%ANS%"=="?"    ( ECHO I am confused        )

Upvotes: 1

Rahul
Rahul

Reputation: 77876

Try this one ... it works perfectly

@ECHO OFF
SET ANS="%1"
IF %ANS%=="" ( ECHO You Entered Nothing
  )
  IF /i %ANS%=="Y" ( ECHO You entered Yes
    )
    IF /i %ANS%=="N" ( ECHO You entered NO
      )
      IF %ANS%=="?" ( ECHO I am confused
        )

Upvotes: 0

Stephan
Stephan

Reputation: 56180

The error message comes from your second IF. If %1 is empty, your first IF gives you "You entered nothing" as intended. Then the second IFline translates to

IF /i ==Y ( ECHO You entered YES

(because %ANS% is empty)

Therefore you get a "( was unexpected at this time).

To correct this, write

IF /i "%ANS%"=="Y" ( ECHO You entered Yes

Upvotes: 1

Related Questions