How to use if - else structure in a batch file?

前端 未结 8 753
南方客
南方客 2020-11-28 03:53

I have a question about if - else structure in a batch file. Each command runs individually, but I couldn\'t use \"if - else\" blocks safely so these parts of my programme d

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 03:56

    I think in the question and in some of the answers there is a bit of confusion about the meaning of this pseudocode in DOS: IF A IF B X ELSE Y. It does not mean IF(A and B) THEN X ELSE Y, but in fact means IF A( IF B THEN X ELSE Y). If the test of A fails, then he whole of the inner if-else will be ignored.

    As one of the answers mentioned, in this case only one of the tests can succeed so the 'else' is not needed, but of course that only works in this example, it isn't a general solution for doing if-else.

    There are lots of ways around this. Here is a few ideas, all are quite ugly but hey, this is (or at least was) DOS!

    @echo off
    
    set one=1
    set two=2
    
    REM Example 1
    
    IF %one%_%two%==1_1 (
       echo Example 1 fails
    ) ELSE IF %one%_%two%==1_2 (
       echo Example 1 works correctly
    ) ELSE (
        echo Example 1 fails
    )
    
    REM Example 2
    
    set test1result=0
    set test2result=0
    
    if %one%==1 if %two%==1 set test1result=1
    if %one%==1 if %two%==2 set test2result=1
    
    IF %test1result%==1 (
       echo Example 2 fails
    ) ELSE IF %test2result%==1 (
       echo Example 2 works correctly
    ) ELSE (
        echo Example 2 fails
    )
    
    REM Example 3
    
    if %one%==1 if %two%==1 (
       echo Example 3 fails
       goto :endoftests
    )
    if %one%==1 if %two%==2 (
       echo Example 3 works correctly
       goto :endoftests
    )
    echo Example 3 fails
    )
    :endoftests
    

提交回复
热议问题