This one is more of a curiosity question, but is there a way in Windows Batch to be able to make an if file.ext exists && if file2.ext exists (echo Yes.) else (echo No.) -type command?
2 Answers
Yes, you can implement AND/OR operator like:
if exist file1.ext ( if exist file2.ext ( echo Yes, both file1.ext and file2.ext exist ) else ( echo No, both file1.ext and file2.ext not exist )
) else ( If exist file2.ext ( echo file1.ext does NOT exist but file2.ext does exist )
)To check if File2.ext does exist and file1.ext not exist then:
if exist file1.ext ( if not exist file2.ext ( echo file1.ext does exist but file2.ext does NOT exist )
)Placement of the Else keywords matter!
Read more:
You do not need if to check if your files exist:
1. Replace if exist && file1 if exist file2 to dir /w file1 file2
dir /w file1.ext file2.ext- Obs.: 1 Outputs:
2. Suppress any possible errors if any or both files do not exist and redirect the output of the command dir to findstr
2>nul dir /w file1.ext file2.ext | findstr /i "file1.ext.*file2.ext" ... - Obs.: 2 Suppress any possible errors using
2>nuland redirect the output with|
3. Use operator:
findstr &&to handlereturn 0both file1.ext and file2.ext existfindstr ||to handlereturn non 0file1.ext or file2.ext (or both) not exist
2>nul dir /w file1.ext file2.ext | findstr /i "file1.ext.*file2.ext" && echo\yEp! || echo\nOp!- Obs.: 3 In
findstrnot to be case-sensitive (capital letters | lower case), use/i, as the string has some spaces between filenames on the same line, use.um or more*characters
... | findstr /i "file1.ext.*file2.ext" && ... - Possible Cases/Outputs from
findstrreturns:
:: Exist file1.ext == True:: Exist file2.ext == True:: Results => Return "0" == echo\yEp!:: Exist file1.ext == False:: Exist file2.ext == False:: Results => Return non "0" == echo\nOp!:: Exist file1.ext == True:: Exist file2.ext == False:: Results => Return non "0" == echo\nOp!:: Exist file1.ext == False:: Exist file2.ext == True:: Results => Return non "0" == echo\nOp!You can also use a for loop to do the same when multiple files need to be checked and what to import is one does not exist, in which case you can immediately move batch processing to a :label when this condition is met, if all files exist, subsequent/following lines will be executed.
@echo off
cd /d "%~dp0"
for %%i in ("file1.ext","file2.ext","file3.ext","file4.ext","file5.ext"
)do if not exist "%%~i" echo\File "%%~i" does Not exist && goto %:^(
:: Run more commands below, because all your files exist...
goto=:EOF
%:^(
:: Run more commands below, because one some of your files don't exist
goto=:EOF- Obs.: 4 After the relevant executions after the
forloop or inside the label%:^(, usegoto=:EOFto move the processing to the End Of File or to another:labelif applicable...
:: Run more commands below, because all your files exist...goto=:EOF%:^(
:: Run more commands below, because one some of your files don't existgoto=:EOFSome further reading:
[√] Dir /?
[√] Findstr /?