0

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.

2
  • Why do you think those are nested if statements? Also, check out the correct syntax for an if-else statement in batch here - the echo statement should be on a new line. Commented Mar 19, 2014 at 17:17
  • Both ways have the same results. Everything works besides the "%ans"=="" generating the "( was unexpected at this time." Commented Mar 19, 2014 at 17:23

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, adding a few quotes here and there solved the problem.
Yes. The reason is that the entire block of IF statements is parsed in one pass, and all syntax must be correct, even if it never gets executed. The later IF statements become invalid if the variable is undefined.
1

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        )

Comments

0

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
        )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.