What is the simplest and/or most readable method to IF
with AND
in a CMD shell? In pseudo code:
IF EXIST file1 AND file2:
then do stuff
ELSE:
do something else
this Q has to be somewhere on SO but my search-fu isn't working for this one. sorry
Equality between two variables/values (==) There are many times when we need to ask the computer if two variables contain an "equal" value (e.g., x == y), or if one variable contains a value equal to a known constant (e.g., x == 5). Equality is represented in the program using the DOUBLE EQUAL signs operator.
%%i is simply the loop variable. This is explained in the documentation for the for command, which you can get by typing for /? at the command prompt.
Checking for the existence of a file can be accomplished by using IF EXIST in a batch file called from the login script, or by using the login script ERRORLEVEL variable with a MAP statement. The COMMAND.COM /C will close the CMD box window automatically after it terminates.
Checking Command Line ArgumentsAnother common use of the 'if' statement is used to check for the values of the command line arguments which are passed to the batch files. The following example shows how the 'if' statement can be used to check for the values of the command line arguments.
IF EXIST A (
IF EXIST B (
ECHO A and B exist
)
)
Assuming you are talking about DOS/Windows batch files, I think you want something like this:
SET do_stuff=false
IF EXIST file1 IF EXIST file2 SET do_stuff=true
IF "%do_stuff%"=="true" (
REM do stuff
) ELSE (
REM do something else
)
The source of the ugliness is that DOS batch file if
statements do not have and and or operators, so you have to either write nested if
statements (which can lead to duplicated code in the then and else clauses), or capture the expression result into a variable and then do an if
statement on its value (lots more lines). I favor the second approach to avoid duplication of code. Perhaps this is all a security feature. :)
I found some good examples here and here (SO, even). But you can also just use the help system built into the shell (help if
or if /?
IIRC).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With