Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if file with certain file extension present in folder using batch script

I want to check a certain file extension in the folder using batch script

Its like,

if exist <any file with extension .elf>
  do something
else
  do something else

Here file name may be anything but only extension(.elf) is important

like image 883
Manas Mohanta Avatar asked Jan 09 '23 01:01

Manas Mohanta


2 Answers

In the simplest case the batch language includes a construct for this task

if exist *.elf (
    :: file exists - do something 
) else (
    :: file does not exist - do something else
)

where the if exist will test for existence of an element in the current or indicate folder that matches the indicated name/wildcard expression.

While in this case it seems you will not need anything else, you should take into consideration that if exist makes no difference between a file and a folder. If the name/wildcard expression that you are using matches a folder name, if exists will evaluate to true.

How to ensure we are testing for a file? The easiest solution is to use the dir command to search for files (excluding folders). If it fails (raises errorlevel), there are no files matching the condition.

dir /a-d *.elf >nul 2>&1 
if errorlevel 1 (
    :: file does not exist - do something
) else (
    :: file exists - do something else
)

Or, using conditional execution (just a little abreviation for the above code)

dir /a-d *.elf >nul 2>&1 && (
    :: file does exist - do something
) || ( 
    :: file does not exist - do something else 
)

What it does is execute a dir command searching for *.elf , excluding folders (/a-d) and sending all the output to nul device, that is, discarding the output. If errorlevel is raised, no matching file has been found.

like image 130
MC ND Avatar answered May 04 '23 09:05

MC ND


as easy as you can think:

if exist *.elf echo yes
like image 21
Stephan Avatar answered May 04 '23 08:05

Stephan