简体   繁体   English

通过扩展名bash检查文件类型的存在

[英]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] $ [-f *。$ fileext]

where fileext is the file extension but that does not seem to work. 其中fileext是文件扩展名,但似乎不起作用。

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. 第二种方法不太整洁,因为显示了任何ls错误,因此我更喜欢方法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 编辑:感谢@Dennis指出了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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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