if 语句帮助 windows 批处理

if 语句帮助 windows 批处理

我正在想办法做类似的事情

if %a%==1&2 goto next

if NOT %a%==1&2 goto start

if %b%==1&2 goto next2

if NOT %b%==1&2 goto next  

但我不知道如何使用 if 语句来检查两个变量,我只能这样做

if %a%==1 goto next

if %a%==2 goto next

if NOT %a%==1 goto start

if NOT %a%==2 goto start

但这看起来真的很混乱,这不是我想要的,所以如果有人能找到解决方案,我很乐意看到它。

答案1

@echo off 

set "_a=3"

echo\%_a%|findstr /be [1-2] >nul && =;(
     goto Next
   );= || goto Start

:Start
echo\here I'm: Start
:: do something here 
goto :eof

:Next
echo\here I'm: Next
:: do something here 
goto :eof


要比较变量和变量 b,假设操作goto NextX如果等于 1 或 2 和/或不同于该值,则转到开始:

@echo off 

set "_a=3"
set "_b=2"

if "%_a%" == "1" (
     goto Next%_a%
    )else if "%_a%" == "2" (
     goto Next%_a%
    )else if "%_b%" == "1" (
     goto Next%_b%
    )else if "%_b%" == "2" (
     goto Next%_b%
    )else goto Start
   
:Start
echo\here I'm: Start
:: do something here 
goto :eof

:Next1
echo\here I'm: Next1
:: do something here 
goto :eof

:Next2
echo\here I'm: Next2
:: do something here 
goto :eof

  • 您可以使用findstr "1 [or] 2" && (do) || do instead
findstr /Begin /End [range 1-2] and the operator for success && (
    does this 
   ) and the operator failure `||` does that

观察:这假设您的变量具有值12任何其他数字,但如果您的变量包含一个或多个字母数字,则将findSTR是:


@echo off 

set "_a=SomeStrings"

echo\%_a%|findstr /eb "SomeStrings OtherSomeStrings" >nul && =;(
     goto Next
   );= || goto Start

:Start
echo\here I'm: Start
:: do something here 
goto :eof

:Next
echo\here I'm: Next
:: do something here 
goto :eof
  • 您可以使用if() else if () else ()
@echo off 

set "_a=3"

if "%a%" == "1" (
      goto Next
    ) else if "%a%" == "2" (
      goto next
    ) else goto Start
    
:Start
echo\here I'm: Start
:: do something here 
goto :eof

:Next
echo\here I'm: Next
:: do something here 
goto :eof

其他资源:

答案2

IF 不支持多个比较。如需实现此目的,请使用如下方法:

    @echo off
:start

::  -- Question the user    
    set /p a=What is A? 

    if %a%==1 goto next
    if %a%==2 goto next

    echo That was an invalid response. Can you try again?
    echo.
    goto start

:next
    echo A was 1 or 2.
    pause

另一个选项是使用命令选择,因为它将确保用户输入 1 或 2:

    @echo off

::  -- Question the user    
    choice /C 12 /M What is A? 

::  -- List these in descending order. 
::  -- They follow the order of items listed in choice. 
::  -- for example: choice /C YN, Y=1, N=2.
    if %errorlevel%==2 goto next
    if %errorlevel%==1 goto next



:next
    echo A was 1 or 2.
    pause

相关内容