Often you may want to use Bash to check if a file has a specific file extension.
You can use the following methods to do so:
Method 1: Check if File Has One Specific Extension
if [[ $my_file == *.txt ]]
then
echo "File extension is .txt"
else
echo "File extension is not .txt"
fi
This particular example will check if the file specified by the path in the $my_file variable has a .txt extension and output the appropriate string as a result.
Method 2: Check if File Has One of Several Specific Extensions
if [[ ( $my_file == *.csv ) || ( $my_file == *.xlsx ) ]]
then
echo "File extension is .csv or .xlsx"
else
echo "File extension is not .csv or .xlsx"
fi
This particular example will check if the file specified by the path in the $my_file variable has a .csv or .xlsx extension and output the appropriate string as a result.
The following examples show how to use each of these methods in practice.
Example 1: Check if File Has One Specific Extension
Suppose that we have a file named players.txt located at the following path:
- c:/users/bobbi/data2/players.txt
Suppose that we would like to check if this file has a .txt extension.
We can use the following syntax to do so:
my_file="c:/users/bobbi/data2/players.txt"
if [[ $my_file == *.txt ]]
then
echo "File extension is .txt"
else
echo "File extension is not .txt"
fi
The following screenshot shows how to use this syntax in practice:

This returns “File extension is .txt” since the file does indeed have a .txt extension.
Example 2: Check if File Has One of Several Specific Extensions
Suppose once again that we have a file named players.txt located at the following path:
- c:/users/bobbi/data2/players.txt
Suppose that we would like to check if this file has a .csv or .xlsx extension.
We can use the following syntax to do so:
my_file="c:/users/bobbi/data2/players.txt"
if [[ ( $my_file == *.csv ) || ( $my_file == *.xlsx ) ]]
then
echo "File extension is .csv or .xlsx"
else
echo "File extension is not .csv or .xlsx"
fi
The following screenshot shows how to use this syntax in practice:

This returns “File extension is not .csv or .xlsx” since the file indeed does not have one of these two specific extensions.
Feel free to replace .csv and .xlsx with any other specific file extensions that you would like to check.
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
