1

Does anyone know why this is not working? I want it to ask for a string, such as 1, 2 or exampletext. Then it checks if the input value is 1, then it changes the variable to ABC, if it's 2, then it changes to DEF, otherwise leave it the same.

@echo off
set /p id="Enter ID: " %=%
IF "%id%" == "1"(
   set id="ABC"
)
ELSE (
   IF "%id%" == "2"(
      set id="DEF"
   )
   ELSE (
      PING 127.0.0.1 -n 0.1 >nul  
   )
)
Start "" "C:\Users\Comp\Desktop\livestreamer-1.5.2-win32\livestreamer.exe" twitch.tv/%id% mobile_High

2 Answers 2

5

Although Joey already indicated the cause of the error, I can't resist the temptation to show you a different method to do this:

@echo off
setlocal EnableDelayedExpansion

rem Define the table of equivalences:
set equiv[1]=ABC
set equiv[2]=DEF

set /p "id=Enter ID: " %=%
if defined equiv[%id%] (
   set id=!equiv[%id%]!
) ELSE (
   PING 127.0.0.1 -n 0.1 >nul  
)
Start "" "C:\Users\Comp\Desktop\livestreamer-1.5.2-win32\livestreamer.exe" twitch.tv/%id% mobile_High

This method use an array. If you are interested in this method, search for "Delayed Expansion" and "Arrays in Batch".

Sign up to request clarification or add additional context in comments.

3 Comments

It uses several environment variables that look like an array ;) – but indeed, that's a nice option if the list of possible values gets longer.
Array? There is no single array in batch. :-)
@Endoro: Excuse me "Ansgar", I forgot that! ;-)
3

You're just missing a few spaces (before the opening parenthesis in the if). And else needs to go on the same line as the closing parenthesis¹:

IF "%id%" == "1" (
   set id=ABC
) ELSE (
   IF "%id%" == "2" (
      set id=DEF
   ) ELSE (
      PING 127.0.0.1 -n 0.1 >nul  
   )
)

Note also that quotes after the = in set are included verbatim in the variable, which isn't what you want here.

You can also simplify a bit:

if "%id%=="1" (
  set id=ABC
) else if "%id%=="2" (
  set id=DEF
) else (
  ping localhost -n 1 >nul
)

¹ Which is even spelled out in help if on the very first page: “The ELSE clause must occur on the same line as the command after the IF.”

1 Comment

Thanks a lot! I didn't know that 1-2 spaces can cause the errors. I'm still new to batch coding.

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.