Saved Bookmarks
| 1. |
Solve : if exist file A or file B? |
|
Answer» I am trying to simplfy script so instead of cheking twice Why don't you just do this? (label :UB doesn't even need to exist) I did that but I thought maybe there is OR which will simplify thisYou don't get a logical OR with the batch IF test. You don't get a logical AND either, but you can mimic this by using two IF TESTS on one line like so Mimic IF exist file1 AND if exist file2 THEN do_something (which doesn't work in batch): IF exist file1 if exist file2 do_something You see how the second IF will only be executed "if" the first one evaluates as true? Well, you can use De Morgan's laws to turn a chain of IF NOTs into the equivalent of OR tests Mimic IF exist file1 OR if exist file2 THEN do_something (which doesn't work in batch): set flag=true IF NOT exist file1 IF NOT exist file2 set flag=false if %flag%=="true" do_something If file1 exists, the first IF NOT test will fail, and the second one will not be executed. the variable %flag% will not be changed, and will stay as "true". This satisfies the OR condition because file1 exists. If file1 does not exist, the first IF NOT test will succeed, and the second one will be executed. If file2 exists, the second IF NOT test will fail, and the %flag% will not be changed, and remains as "true". This satisfies the OR condition because file2 exists. if file1 does not exist, the first IF test will succeed, and the second IF test will then be executed. If file2 does not exist either, the second test will succeed, and the variable %flag% be changed to "false". Thus the OR test fails because neither file exists. The problem is that the above way of doing it uses 3 lines whereas this only uses 2 lines: if exist file1 do_something if exist file2 do_ something However, you can chain a lot of IF NOTS in one line, where the savings of lines will be greater. Test if a number is one of these: 4, 6, 9, 47, 1234 or 9999, in 3 lines instead of 6: echo off set /p "x=Input a number " set flag=true if not "%x%"=="4" if not "%x%"=="6" if not "%x%"=="9" if not "%x%"=="47" if not "%x%"=="1234" if not "%x%"=="9999" set flag=false if "%flag%"=="true" (echo PASS) else (echo FAIL) For that demo, you don't need this, so I took it out: Quote setlocal enabledelayedexpansionNote: The maximum length of any command line (or variable) within CMD is 8191 characters. A single line should not exceed 8192 characters, even after the expansion of %var% or !var! expressions, else you got an error. |
|