Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the extension of a filename in a bash script?

People also ask

How do you find the extension of a file in bash?

Using Bash, there's also ${file%. *} to get the filename without the extension and ${file##*.} to get the extension alone. That is, file="thisfile.

How do I check the extension of a file in Linux?

To find out file types we can use the file command. Using the -s option we can read the block or character special file. Using -F option will use string as separator instead of “:”. We can use the –extension option to print a slash-separated list of valid extensions for the file type found.


Make

if [ "$file" == "*.txt" ]

like this:

if [[ $file == *.txt ]]

That is, double brackets and no quotes.

The right side of == is a shell pattern. If you need a regular expression, use =~ then.


I think you want to say "Are the last four characters of $file equal to .txt?" If so, you can use the following:

if [ "${file: -4}" == ".txt" ]

Note that the space between file: and -4 is required, as the ':-' modifier means something different.


You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

file -ib "$file"

Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.


You could also do:

   if [ "${FILE##*.}" = "txt" ]; then
       # operation for txt files here
   fi

You can use the "file" command if you actually want to find out information about the file rather than rely on the extensions.

If you feel comfortable with using the extension you can use grep to see if it matches.


Similar to 'file', use the slightly simpler 'mimetype -b' which will work no matter the file extension.

if [ $(mimetype -b "$MyFile") == "text/plain" ]
then
  echo "this is a text file"
fi

Edit: you may need to install libfile-mimeinfo-perl on your system if mimetype is not available