Tommy
Tommy

Reputation: 611

Checking existence of file types via extensions bash

I need to test if various file types exist in a directory.

I've tried

$ [ -f *.$fileext]

where fileext is the file extension but that does not seem to work.

Both of these methods work

function checkext() {
fileext=$1

ls *.$fileext>/dev/null 2>&1

if [ $? -eq 0 ]
then
  echo "We have $fileext files!"
else
  echo "We don't have any $fileext files!"
fi
}

and

function checkext2() {
extention=$1

filescheck=(`ls *.$1`)
len=${#filescheck[*]}


if [ $len -gt 0 ]
then
 echo "We have $extention files!"
else
 if [ $len -eq 0 ]
 then
   echo "We don't have any $extention files!"
 else
   echo "Error"
 fi
fi
}

The second method is less tidy as any ls error is shown so I prefer method 1.

Could people please suggest any improvements, more elegant solutions e.t.c

Upvotes: 1

Views: 1305

Answers (2)

gsbabil
gsbabil

Reputation: 7703

#!/bin/bash

filetypes="lyx eps pdf"

for type in $filetypes
do
        files=$(ls *.${type} 2>/dev/null)
        if [ ! -z "$files" ]
        then
                echo "filetype: [$type] exists"
        fi  
done

Upvotes: 0

Michael Lowman
Michael Lowman

Reputation: 3068

what about

shopt -s nullglob
[ -z "`echo *.$ext`" ] || echo "YAY WE HAVE FILES"

Edit: thanks to @Dennis for pointing out the nullglob

Upvotes: 3

Related Questions