有条件的批次转到

时间:2018-08-13 11:19:21

标签: batch-file cmd

我想调用参数为true的特定子例程。如果两个参数均为false,则退出。我尝试了不同的方法,但是找不到解决我问题的方法。

我有以下情况:

echo OFF
set APP=TRUE
set BPP=TRUE

IF /i "%APP%"=="true" goto sub1
IF /i "%APP%"=="true" goto sub2

echo Both are set false
goto CLOSE

:sub1
echo This is sub1

:sub2
echo This is sub2

:CLOSE
echo Nothing is selected 
exit /B 1

方案如下: 如果只有APP为true,我只希望执行sub1,如果只有BPP为true,那么我仅希望执行sub2。如果APP和BPP都为true,则必须先执行sub1,然后必须执行sub2。但是,如果APP和BPP都设置为false,则必须执行CLOSE。

谢谢。

3 个答案:

答案 0 :(得分:5)

使用call(返回)代替goto。另外,您忘了结束子例程,因此代码将“通过”运行:

echo OFF
set APP=TRUE
set BPP=TRUE

if /i "%APP%%BPP%"=="falsefalse" (
  echo Both are set false
  echo Nothing is selected 
  exit /B 1
)   
IF /i "%APP%"=="true" call :sub1
IF /i "%BPP%"=="true" call :sub2
echo done.
exit /b 0

:sub1
echo This is sub1
goto :eof

:sub2
echo This is sub2
goto :eof

答案 1 :(得分:2)

您只需在:sub1中添加另一个条件:

@echo OFF
set "APP=TRUE"
set "BPP=TRUE"

if /I "%APP%"=="true" goto :sub1
if /I "%BPP%"=="true" goto :sub2

echo Both are set to FALSE
goto :CLOSE

:sub1
echo This is :sub1
if /I not "%BPP%"=="true" goto :end

:sub2
echo This is :sub2
goto :end

:CLOSE
echo Nothing is selected
exit /B 1

:end
echo At least one is set to TRUE

或者您可以只反转if查询并有条件地跳过代码部分;要检测两个代码节:sub1:sub2是否都被跳过,可以使用类似标志的变量:

@echo OFF
set "APP=TRUE"
set "BPP=TRUE"
set "FLAG="

if /I not "%APP%"=="true" goto :sub2
:sub1
echo This is :sub1
set "FLAG=#"

if /I not "%BPP%"=="true" goto :skip
:sub2
echo This is :sub2
set "FLAG=#"

:skip
if defined FLAG goto :end
echo Both are set to FALSE

:CLOSE
echo Nothing is selected
exit /B 1

:end
echo At least one is set to TRUE

您也可以将goto替换为call,并使用标志样式的变量来做到这一点:

@echo OFF
set "APP=TRUE"
set "BPP=TRUE"
set "FLAG="

if /I "%APP%"=="true" call :sub1
if /I "%BPP%"=="true" call :sub2

if defined FLAG goto :end
echo Both are set to FALSE
goto :CLOSE

:sub1
echo This is :sub1
set "FLAG=#"
goto :EOF

:sub2
echo This is :sub2
set "FLAG=#"
goto :EOF

:CLOSE
echo Nothing is selected
exit /B 1

:end
echo At least one is set to TRUE

答案 2 :(得分:1)

这应该做到:

echo OFF
set APP=TRUE
set BPP=TRUE

IF /i "%APP%"=="true" goto sub1
IF /i "%BPP%"=="true" goto sub2

echo Both are set false
goto CLOSE

:sub1
echo This is sub1
IF /i "%BPP%"=="false" goto CLOSE

:sub2
echo This is sub2

:CLOSE
echo Nothing is selected 
exit /B 1

请注意在sub1末尾添加了条件。