Checking existence of file types via extensions bash.

Posted by Tommy on Stack Overflow See other posts from Stack Overflow or by Tommy
Published on 2011-01-05T15:19:27Z Indexed on 2011/01/06 1:53 UTC
Read the original article Hit count: 504

Filed under:

Hi,

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

© Stack Overflow or respective owner

Related posts about bash