Using multiple IF statements in a batch file

后端 未结 5 1998
情深已故
情深已故 2021-02-01 07:28

When using more than 1 IF statement, is there a special guideline that should be followed? Should they be grouped? Should I use parenthesis to wrap the command(s)?

An ex

5条回答
  •  一向
    一向 (楼主)
    2021-02-01 07:37

    The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.

    When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:

    SET AND=IF
    
    IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt
    

    Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.

    When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:

    SET AND=IF
    SET THEN=(
    SET ELSE=) ELSE (
    SET NOELSE=
    SET ENDIF=)
    SET BEGIN=(
    SET END=)
    SET RETURN=EXIT /B
    

    These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:

    IF EXIST "somefile.txt" %THEN%
      IF EXIST "someotherfile.txt" %THEN%
        SET var="somefile.txt,someotherfile.txt"
      %NOELSE%
      %ENDIF%
    %NOELSE%
    %ENDIF%
    
    IF EXIST "%~1" %THEN%
      SET "result=%~1"
    %ELSE%
      SET "result="
    %ENDIF%
    

    I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.

提交回复
热议问题