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

theman_on_vista picture theman_on_vista · Jan 2, 2009 · Viewed 231.1k times · Source

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?

Answer

user49586 picture user49586 · Jan 2, 2009

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.