简体   繁体   中英

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 etc

what about

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

Edit: thanks to @Dennis for pointing out the nullglob

#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM