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

前端 未结 8 709
南方客
南方客 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 04:13

    AFAIK you can't do an if else in batch like you can in other languages, it has to be nested if's.

    Using nested if's your batch would look like

    IF %F%==1 IF %C%==1(
        ::copying the file c to d
        copy "%sourceFile%" "%destinationFile%"
        ) ELSE (
            IF %F%==1 IF %C%==0(
            ::moving the file c to d
            move "%sourceFile%" "%destinationFile%"
            ) ELSE (
                IF %F%==0 IF %C%==1(
                ::copying a directory c from d, /s:  boş olanlar hariç, /e:boş olanlar dahil
                xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
                ) ELSE (
                    IF %F%==0 IF %C%==0(
                    ::moving a directory
                    xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
                    rd /s /q "%sourceMoveDirectory%"
                    )
                )
            )
        )
    

    or as James suggested, chain your if's, however I think the proper syntax is

    IF %F%==1 IF %C%==1(
        ::copying the file c to d
        copy "%sourceFile%" "%destinationFile%"
        )
    
    0 讨论(0)
  • 2020-11-28 04:15

    A little bit late and perhaps still good for complex if-conditions, because I would like to add a "done" parameter to keep a if-then-else structure:

    set done=0
    if %F%==1 if %C%==0 (set done=1 & echo found F=1 and C=0: %F% + %C%)
    if %F%==2 if %C%==0 (set done=1 & echo found F=2 and C=0: %F% + %C%)
    if %F%==3 if %C%==0 (set done=1 & echo found F=3 and C=0: %F% + %C%)
    if %done%==0 (echo do something)
    
    0 讨论(0)
提交回复
热议问题