Bash: How to Check if Specific File Type Exists in Directory


Often you may want to use Bash to check if a specific file type exists in a directory.

You can use the following syntax to do so:

my_files=(`find ./ -maxdepth 1 -name "*.csv"`)

if [ ${#my_files[@]} -gt 0 ]; then 
    echo true 
else 
    echo false
fi

This particular example will check if the current directory contains any .csv files and return either true or false as a result.

This syntax first uses the find statement to find all .csv files in the current directory and store them in an array named my_files.

It then uses and if else statement to check if the length of the array named my_files is greater than zero, which is an indication of whether or not the directory contained any files with the file type that we specified.

The following example shows how to use this syntax in practice.

Example: Check if File Type Exists in Directory Using Bash

Suppose that we would like to check if our current directory contains any .csv files.

Before we do so, we can use the ls statement to first view all of the filenames in our current directory:

We can see that the current directory contains the following filenames:

  • athletes.csv
  • managers.txt
  • owners.txt
  • players.txt
  • stats.csv

We can then use the following syntax to check if the current directory contains any .csv files:

my_files=(`find ./ -maxdepth 1 -name "*.csv"`)

if [ ${#my_files[@]} -gt 0 ]; then 
    echo true 
else 
    echo false
fi

The following screenshot shows how to use this syntax in practice:

Bash check if file type exists in directory

This returns true since the current directory does indeed contain at least one .csv file.

Note: Feel free to use the echo statement to return different output values other than true and false if you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to List All Files in Folder Without Extension
Bash: How to Rename Extension of Multiple Files
Bash: How to Find All Files with Specific Extension

Leave a Reply