Check whether a certain file type/extension exists in directory

Viewed 111243

How would you go about telling whether files of a specific extension are present in a directory, with bash?

Something like

if [ -e *.flac ]; then 
echo true; 
fi 
15 Answers

For completion, with zsh:

if [[ -n *.flac(#qN) ]]; then
  echo true
fi

This is listed at the end of the Conditional Expressions section in the zsh manual. Since [[ disables filename globbing, we need to force filename generation using (#q) at the end of the globbing string, then the N flag (NULL_GLOB option) to force the generated string to be empty in case there’s no match.

Here's a fairly simple solution:

if [ "$(ls -A | grep -i \\.flac\$)" ]; then echo true; fi

As you can see, this is only one line of code, but it works well enough. It should work with both bash, and a posix-compliant shell like dash. It's also case-insensitive, and doesn't care what type of files (regular, symlink, directory, etc.) are present, which could be useful if you have some symlinks, or something.

I tried this:

if [ -f *.html ]; then
    echo "html files exist"
else
    echo "html files dont exist"
fi

I used this piece of code without any problem for other files, but for html files I received an error:

[: too many arguments

I then tried @JeremyWeir's count solution, which worked for me:

count=`ls -1 *.flac 2>/dev/null | wc -l`
if [ $count != 0 ]
then 
echo true
fi 

Keep in mind you'll have to reset the count if you're doing this in a loop:

count=$((0))

This should work in any borne-like shell out there:

if [ "$(find . -maxdepth 1 -type f | grep -i '.*\.flac$')" ]; then
    echo true
fi

This also works with the GNU find, but IDK if this is compatible with other implementations of find:

if [ "$(find . -maxdepth 1 -type f -iname \*.flac)" ]; then
    echo true
fi
Related