4

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

1
  • if should be like this if exist *.elf do ( file exist - do something ), you should use do keyword Commented Feb 17, 2021 at 10:58

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

if should be like this if exist *.elf do ( file does exist - do something ), you should use do keyword
@MȍhǟmmǟdȘamȋm, no, it should not. In batch files for command needs the do clause but if command syntax doesn't include a do clause.
if exist *.elf do this is working for me fine, if with do, without do in my case it is not working.
3

as easy as you can think:

if exist *.elf echo yes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.