Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch - If, ElseIf, Else

Whats wrong with this code?

IF "%language%" == "de" (
    goto languageDE
) ELSE (
    IF "%language%" == "en" (
    goto languageEN
) ELSE (
    echo Not found.
)

I'm not really good in Batch..

like image 365
Underbytex Avatar asked Aug 19 '14 13:08

Underbytex


People also ask

Does batch have else if?

However, you can't use else if in batch scripting. Instead, simply add a series of if statements: if %x%==5 if %y%==5 (echo "Both x and y equal 5.")

What is NEQ in batch file?

NEQ - not equal. LSS - less than. LEQ - less than or equal. GTR - greater than. GEQ - greater than or equal.

How do I pause a batch file?

You can insert the pause command before a section of the batch file that you might not want to process. When pause suspends processing of the batch program, you can press CTRL+C and then press Y to stop the batch program.

Is it possible to apply if function in CMD?

If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause. When a program stops, it returns an exit code.


3 Answers

@echo off
title Test

echo Select a language. (de/en)
set /p language=

IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN

echo Not found.
goto commonexit

:languageDE
echo German
goto commonexit

:languageEN
echo English
goto commonexit

:commonexit
pause

The point is that batch simply continues through instructions, line by line until it reaches a goto, exit or end-of-file. It has no concept of sections to control flow.

Hence, entering de would jump to :languagede then simply continue executing instructions until the file ends, showing de then en then not found.

like image 50
Magoo Avatar answered Oct 16 '22 19:10

Magoo


@echo off

set "language=de"

IF "%language%" == "de" (
    goto languageDE
) ELSE (
    IF "%language%" == "en" (
        goto languageEN
    ) ELSE (
        echo Not found.
    )
)

:languageEN
:languageDE

echo %language%

This works , but not sure how your language variable is defined.Does it have spaces in its definition.

like image 25
npocmaka Avatar answered Oct 16 '22 19:10

npocmaka


batchfiles perform simple string substitution with variables. so, a simple

goto :language%language%
echo notfound
...

does this without any need for if.

like image 9
ths Avatar answered Oct 16 '22 19:10

ths