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

I am writing a nightly build script in bash.
Everything is fine and dandy except for one little snag:


#!/bin/bash

for file in "$PATH_TO_SOMEWHERE"; do
      if [ -d $file ]
      then
              # do something directory-ish
      else
              if [ "$file" == "*.txt" ]       #  this is the snag
              then
                     # do something txt-ish
              fi
      fi
done;

My problem is determining the file extension and then acting accordingly. I know the issue is in the if-statement, testing for a txt file.

How can I determine if a file has a .txt suffix?


Solution 1:

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.

Solution 2:

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.

Solution 3:

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.

Solution 4:

You could also do:

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

Solution 5:

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.