IF… 또는 IF… Windows 배치 파일에서
Windows 배치 파일에 IF OR IF 조건문을 작성하는 방법이 있습니까?
예를 들면 :
IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE
zmbq 솔루션은 좋지만 FOR DO (...) 루프와 같은 코드 블록 내부와 같은 모든 상황에서 사용할 수는 없습니다.
대안은 인디케이터 변수를 사용하는 것입니다. 정의되지 않도록 초기화 한 다음 OR 조건 중 하나가 참인 경우에만 정의하십시오. 그런 다음 IF DEFINED를 최종 테스트로 사용합니다. 지연된 확장을 사용할 필요가 없습니다.
FOR ..... DO (
set "TRUE="
IF cond1 set TRUE=1
IF cond2 set TRUE=1
IF defined TRUE (
...
) else (
...
)
)
arasmussen이 첫 번째 조건이 참이면 조금 더 빠르게 수행 할 수 있다는 근거로 사용하는 ELSE IF 논리를 추가 할 수 있지만 절대 신경 쓰지 않습니다.
부록 -이것은 IF 문에서 OR 사용 WinXP 배치 스크립트 와 거의 동일한 답변이있는 중복 질문입니다.
최종 부록 -변수가 값 목록 중 하나인지 테스트하는 데 가장 좋아하는 기술을 거의 잊었습니다. 구분 된 허용 값 목록을 포함하는 테스트 변수를 초기화 한 다음 검색 및 바꾸기를 사용하여 변수가 목록 내에 있는지 테스트합니다. 이것은 매우 빠르고 임의로 긴 목록에 최소한의 코드를 사용합니다. 지연된 확장 (또는 CALL %% VAR %% 트릭)이 필요합니다. 또한 테스트는 케이스에 민감하지 않습니다.
set "TEST=;val1;val2;val3;val4;val5;"
if "!TEST:;%VAR%;=!" neq "!TEST!" (echo true) else (echo false)
위의 내용은 VAR에이 포함되어 있으면 실패 할 수 =
있으므로 테스트는 절대 불가능하지 않습니다.
VAR의 현재 값에 액세스하기 위해 지연된 확장이 필요한 블록 내에서 테스트를 수행하는 경우
for ... do (
set "TEST=;val1;val2;val3;val4;val5;"
for /f %%A in (";!VAR!;") do if "!TEST:%%A=!" neq "!TEST!" (echo true) else (echo false)
)
VAR 내에서 예상되는 값에 따라 "delims ="와 같은 FOR 옵션이 필요할 수 있습니다.
위의 전략은 =
코드를 조금 더 추가하여 VAR 에서도 안정적으로 만들 수 있습니다 .
set "TEST=;val1;val2;val3;val4;val5;"
if "!TEST:;%VAR%;=!" neq "!TEST!" if "!TEST:;%VAR%;=;%VAR%;"=="!TEST!" echo true
그러나 이제 우리는 표시기 변수를 추가하지 않는 한 ELSE 절을 제공하는 기능을 잃었습니다. 코드는 약간 "보기 흉하게"보이기 시작했지만 VAR이 임의의 수의 대소 문자를 구분하지 않는 옵션 중 하나인지 테스트하는 데 가장 신뢰할 수있는 방법이라고 생각합니다.
마지막으로 각 값에 대해 하나의 IF를 수행해야하기 때문에 약간 느리다고 생각하는 더 간단한 버전이 있습니다. Aacini는 이전에 언급 된 링크에서 수락 된 답변에 대한 의견으로이 솔루션을 제공했습니다.
for %%A in ("val1" "val2" "val3" "val4" "val5") do if "%VAR%"==%%A do echo true
값 목록에는 * 또는? 문자 및 값과 %VAR%
따옴표를 포함해서는 안됩니다. (가) 경우 따옴표 문제가 발생할 %VAR%
또한 공백이나 같은 특수 문자가 포함되어 ^
, &
이 솔루션은 표시기 변수를 추가하지 않는 한이 ELSE 절에 대한 옵션을 제공하지 않습니다이다와 등 또 다른 한계를. 장점은 IF /I
옵션의 유무에 따라 대소 문자를 구분하거나 구분하지 않을 수 있다는 것입니다.
나는 그렇게 생각하지 않는다. 두 개의 IF 및 GOTO를 동일한 레이블로 사용하십시오.
IF cond1 GOTO foundit
IF cond2 GOTO foundit
ECHO Didn't found it
GOTO end
:foundit
ECHO Found it!
:end
이 게시물에 감사 드리며 많은 도움이되었습니다.
도움이 될 수 있다면 Dunno는 문제가 있었으며 덕분 에이 부울 등가를 기반으로 해결하는 또 다른 방법이라고 생각하는 것을 발견했습니다.
"A 또는 B"는 "아님 (A가 아니라 B가 아님)"과 동일합니다.
그러므로:
IF [%var%] == [1] OR IF [%var%] == [2] ECHO TRUE
된다 :
IF not [%var%] == [1] IF not [%var%] == [2] ECHO FALSE
이 질문이 조금 더 오래된 경우에도 :
사용하고 싶다면 if cond1 or cond 2
-복잡한 루프 나 그런 것들을 사용해서는 안됩니다.
단순함 ifs
과 결합 된 후 둘 다 제공합니다 goto
. 이는 암시 적 또는입니다.
//thats an implicit IF cond1 OR cond2 OR cond3
if cond1 GOTO doit
if cond2 GOTO doit
if cond3 GOTO doit
//thats our else.
GOTO end
:doit
echo "doing it"
:end
goto없이 "inplace"작업이 없으면 모든 조건이 일치하면 작업을 3 번 실행할 수 있습니다.
간단한 "FOR"을 한 줄에 사용하여 "or"조건을 사용할 수 있습니다.
FOR %%a in (item1 item2 ...) DO IF {condition_involving_%%a} {execute_command}
귀하의 사례에 적용 :
FOR %%a in (1 2) DO IF %var%==%%a ECHO TRUE
더 없다 IF <arg> OR
거나 ELIF
또는 ELSE IF
그러나, 배치에 ...
이전 IF의 ELSE 안에 다른 IF를 중첩 해보십시오.
IF <arg> (
....
) ELSE (
IF <arg> (
......
) ELSE (
IF <arg> (
....
) ELSE (
)
)
IF를 간접적으로 사용하여 목표를 달성 할 수 있습니다.
다음은 일관성없는 레이블 및 GOTO없이 CMD 배치에서 매우 간결하고 논리적으로 작성할 수있는 복잡한 표현식의 예입니다.
() 괄호 사이의 코드 블록은 CMD에서 (심각한) 종류의 서브 쉘로 처리됩니다. 블록에서 나오는 종료 코드는 블록이 더 큰 부울 표현식에서 재생하는 참 / 거짓 값을 결정하는 데 사용됩니다. 이러한 코드 블록을 사용하여 임의로 큰 부울 식을 작성할 수 있습니다.
간단한 예
각 블록은 전체 표현식의 값이 결정되거나 제어가 튀어 나올 때까지 (예 : GOTO를 통해) 참 (예 : 블록의 마지막 문이 실행 된 후 ERRORLEVEL = 0) / 거짓으로 확인됩니다.
((DIR c:\xsgdde /w) || (DIR c:\ /w)) && (ECHO -=BINGO=-)
복잡한 예
이것은 처음에 제기 된 문제를 해결합니다. 각 블록에서 여러 문장이 가능하지만 || || || 표현은 가능한 한 읽을 수 있도록 간결하게하는 것이 좋습니다. ^는 CMD 배치의 이스케이프 문자이며 행 끝에 배치되면 EOL을 이스케이프하고 CMD가 다음 행에서 현재 배치의 명령문을 계속 읽도록 지시합니다.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
(
(CALL :ProcedureType1 a b) ^
|| (CALL :ProcedureType2 sgd) ^
|| (CALL :ProcedureType1 c c)
) ^
&& (
ECHO -=BINGO=-
GOTO :EOF
)
ECHO -=no bingo for you=-
GOTO :EOF
:ProcedureType1
IF "%~1" == "%~2" (EXIT /B 0) ELSE (EXIT /B 1)
GOTO :EOF (this line is decorative as it's never reached)
:ProcedureType2
ECHO :ax:xa:xx:aa:|FINDSTR /I /L /C:":%~1:">nul
GOTO :EOF
OR 논리를 평가하고 단일 값을 반환하는 함수를 사용할 수 있습니다.
@echo off
set var1=3
set var2=5
call :logic_or orResult "'%var1%'=='4'" "'%var2%'=='5'"
if %orResult%==1 (
echo At least one expression is true
) ELSE echo All expressions are false
exit /b
:logic_or <resultVar> expression1 [[expr2] ... expr-n]
SETLOCAL
set "logic_or.result=0"
set "logic_or.resultVar=%~1"
:logic_or_loop
if "%~2"=="" goto :logic_or_end
if %~2 set "logic_or.result=1"
SHIFT
goto :logic_or_loop
:logic_or_end
(
ENDLOCAL
set "%logic_or.resultVar%=%logic_or.result%"
exit /b
)
If %x%==1 (
If %y%==1 (
:: both are equal to 1.
)
)
여러 변수가 같은 값인지 확인하기위한 것입니다. 다음은 두 변수 중 하나입니다.
If %x%==1 (
:: true
)
If %x%==0 (
If %y%==1 (
:: true
)
)
If %x%==0 (
If %y%==0 (
:: False
)
)
나는 내 머리면 정상에서 그것을 생각했습니다. 더 압축 할 수 있습니다.
I realize this question is old, but I wanted to post an alternate solution in case anyone else (like myself) found this thread while having the same question. I was able to work around the lack of an OR operator by echoing the variable and using findstr to validate.
for /f %%v in ('echo %var% ^| findstr /x /c:"1" /c:"2"') do (
if %errorlevel% equ 0 echo true
)
While dbenham's answer is pretty good, relying on IF DEFINED
can get you in loads of trouble if the variable you're checking isn't an environment variable. Script variables don't get this special treatment.
While this might seem like some ludicrous undocumented BS, doing a simple shell query of IF
with IF /?
reveals that,
The DEFINED conditional works just like EXIST except it takes an environment variable name and returns true if the environment variable is defined.
In regards to answering this question, is there a reason to not just use a simple flag after a series of evaluations? That seems the most flexible OR
check to me, both in regards to underlying logic and readability. For example:
Set Evaluated_True=false
IF %condition_1%==true (Set Evaluated_True=true)
IF %some_string%=="desired result" (Set Evaluated_True=true)
IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)
IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)
Obviously, they can be any sort of conditional evaluation, but I'm just sharing a few examples.
If you wanted to have it all on one line, written-wise, you could just chain them together with &&
like:
Set Evaluated_True=false
IF %condition_1%==true (Set Evaluated_True=true) && IF %some_string%=="desired result" (Set Evaluated_True=true) && IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)
IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)
Never got exist to work.
I use if not exist g:xyz/what goto h: Else xcopy c:current/files g:bu/current There are modifiers /a etc. Not sure which ones. Laptop in shop. And computer in office. I am not there.
Never got batch files to work above Windows XP
Realizing this is a bit of an old question, the responses helped me come up with a solution to testing command line arguments to a batch file; so I wanted to post my solution as well in case anyone else was looking for a similar solution.
First thing that I should point out is that I was having trouble getting IF ... ELSE statements to work inside of a FOR ... DO clause. Turns out (thanks to dbenham for inadvertently pointing this out in his examples) the ELSE statement cannot be on a separate line from the closing parens.
So instead of this:
FOR ... DO (
IF ... (
)
ELSE (
)
)
Which is my preference for readability and aesthetic reasons, you have to do this:
FOR ... DO (
IF ... (
) ELSE (
)
)
Now the ELSE statement doesn't return as an unrecognized command.
Finally, here's what I was attempting to do - I wanted to be able to pass several arguments to a batch file in any order, ignoring case, and reporting/failing on undefined arguments passed in. So here's my solution...
@ECHO OFF
SET ARG1=FALSE
SET ARG2=FALSE
SET ARG3=FALSE
SET ARG4=FALSE
SET ARGS=(arg1 Arg1 ARG1 arg2 Arg2 ARG2 arg3 Arg3 ARG3)
SET ARG=
FOR %%A IN (%*) DO (
SET TRUE=
FOR %%B in %ARGS% DO (
IF [%%A] == [%%B] SET TRUE=1
)
IF DEFINED TRUE (
SET %%A=TRUE
) ELSE (
SET ARG=%%A
GOTO UNDEFINED
)
)
ECHO %ARG1%
ECHO %ARG2%
ECHO %ARG3%
ECHO %ARG4%
GOTO END
:UNDEFINED
ECHO "%ARG%" is not an acceptable argument.
GOTO END
:END
Note, this will only report on the first failed argument. So if the user passes in more than one unacceptable argument, they will only be told about the first until it's corrected, then the second, etc.
참고URL : https://stackoverflow.com/questions/8438511/if-or-if-in-a-windows-batch-file
'program story' 카테고리의 다른 글
GNU의 재귀 와일드 카드는? (0) | 2020.10.05 |
---|---|
intellij 아이디어 실행 구성 백업 (0) | 2020.10.05 |
Google App Engine의 자바 용 JDO와 JPA (0) | 2020.10.05 |
Jasper 보고서가있는 JVM에서 글꼴을 사용할 수 없습니다. (0) | 2020.10.05 |
PHP 정규식 : 끝 구분 기호 '^'가 없습니다. (0) | 2020.10.05 |