Why need an extra bracket in CMD before the else statement?

Why this code does not work?

if exist "D:\Test1" if exist "D:\Test2" (
echo OK
) else (
echo Error
)
pause

This code works but I don't know why this extra brace?

if exist "D:\Test1" if exist "D:\Test2" (
echo OK
)
) else (
echo Error
)
pause

Please help

1 answer

  • answered 2019-12-09 15:42 aschipfl

    For the first approach, think about what happens when the first condition if exist "D:\Test1" is not fulfilled. It might help you when you insert more parentheses and use indentation:

    if exist "D:\Test1" (
        if exist "D:\Test2" (
            echo OK
        ) else (
            echo Error
        )
    )
    

    You may now realise that the else block refers to the inner if condition but not to the outer one, so you need another else clause to return the text Error if any of the files/directories D:\Test1 or D:\Test2 do not exist.

    if exist "D:\Test1" (
        if exist "D:\Test2" (
            echo OK
        ) else (
            echo Error
        )
    ) else (
        echo Error
    )
    

    An alternative way is to use goto to avoid multiple similar else branches, like in this example:

    if exist "D:\Test1" (
        if exist "D:\Test2" (
            echo OK
            goto :CONTINUE
        )
    )
    echo Error
    goto :ERROR
    :CONTINUE
    

    ...or more compact:

    if exist "D:\Test1" if exist "D:\Test2" (echo OK) & goto :CONTINUE
    echo Error
    goto :ERROR
    :CONTINUE
    

    Hint:
    If the tested items are directories add a trailing \, so the condition is true only for directories but not for files; without trailing \ the condition is true for both files and directories.


    The second approach is wrong syntax, because the first ) completes the first if block (actually the inner if condition), and the rest constitutes orphaned fragments like ) else ( and ), which do not execute (interestingly they even do not throw syntax error; these fragments will lead to unexpected behaviour as soon as the whole code portion is placed within another parenthesised block of code).