Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmd: if exist A and B then

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

like image 597
matt wilkie Avatar asked Jan 30 '13 20:01

matt wilkie


People also ask

What does == mean in CMD?

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.

What does %% I mean?

%%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.

How do you check if a file exists or not in CMD?

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.

Can you use if statements in CMD?

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.


2 Answers

IF EXIST A (
    IF EXIST B (
        ECHO A and B exist
        )
    )
like image 73
Shirulkar Avatar answered Sep 25 '22 12:09

Shirulkar


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).

like image 39
Randall Cook Avatar answered Sep 25 '22 12:09

Randall Cook