Using multiple IF statements in a batch file

后端 未结 5 2051
情深已故
情深已故 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:47

    Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.

    For the OP's question it sounds like you require two specific files to exist. Just use a tally:

    IF EXIST somefile.txt (
        set /a file1_status=1
    )
    
    IF EXIST someotehrfile.txt (
        set /a file2_status=1
    )
    
    set /a file_status_result=file1_status + file2_status
    
    if %file_status_result% equ 2 (
        goto somefileexists
    )
    
    goto exit
    
    :somefileexists
    IF EXIST someotherfile.txt SET var=...
    
    :exit
    

    My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.

提交回复
热议问题