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
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
精彩评论