[solved] if A or B

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
alasdair
Posts: 4
Joined: 27 Sep 2007 04:20

[solved] if A or B

#1 Post by alasdair » 01 Oct 2007 01:01

is there any way of getting an if A or B (do something) construct?

jeb
Expert
Posts: 1041
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

#2 Post by jeb » 05 Oct 2007 14:19

Hi,

yes there is a possible way.
if you want to know if x=3 or y=4 try this.

@echo off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

set x=%1
set y=%2
call :logic_or "%x%==3" "%y%==4" result

if %result%==1 ( echo a or b is true ) else ( echo both wrong)
goto:eof

::::::::::::::::::::::
:logic_or
set %~3=0
if %~1 set %~3=1
if %~2 set %~3=1
goto :eof

alasdair
Posts: 4
Joined: 27 Sep 2007 04:20

Wow

#3 Post by alasdair » 05 Oct 2007 15:29

this dos command shell is wierd. But thanks for the tip, I think I will use it because I have had to duplicate a lot of code. This looks almost like a gosub (like we used to use so many years ago ..)

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

#4 Post by DosItHelp » 30 Jan 2008 23:41

Yes batch is wired sometimes and makes one thinking. Nice function jep!
How about this inline alternative:

Code: Select all

set "true="
if "%~1"=="a" set "true=Y"
if "%~1"=="b" set "true=Y"
if "%~1"=="c" set "true=Y"
if defined true (echo.At least one condition was TRUE) else (echo.All FALSE)


The good think about it:
The number of OR conditions is not limited, just add more if [COND] set "true=Y".
It workes within blocks, i.e.:

Code: Select all

for /L %%N in (1,1,6) do (
    set "true="
    if "%%N"=="1" set "true=Y"
    if "%%N"=="2" set "true=Y"
    if "%%N"=="3" set "true=Y"
    if "%%N"=="5" set "true=Y"
    if defined true (echo %%N is prime) else (echo %%N is not prime)
)
Output:
1 is prime
2 is prime
3 is prime
4 is not prime
5 is prime
6 is not prime

Enjoy :wink:

jeb
Expert
Posts: 1041
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

#5 Post by jeb » 31 Jan 2008 03:08

Ok, I prefer functions instead of too much inline code.

So here my simple solution.

The good think about it:
The number of OR conditions is not limited, just add a compare statement. :)

Code: Select all

@echo off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

for /L %%N in (1,1,6) do (
    call :logic_or result "%%N==1" "%%N==2" "%%N==3" "%%N==5"
    if $!result!==$1 (echo %%N is prime) else (echo %%N is not prime)
)
goto :eof

:::::::::::::::::::::::::
: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%
  goto :eof
)


good look
Jan Erik

Post Reply