我试图检查一个文件是否存在,但与通配符。以下是我的例子:

if [ -f "xorg-x11-fonts*" ]; then
    printf "BLAH"
fi

我也试过不加双引号。


当前回答

试试这个

fileTarget="xorg-x11-fonts*"

filesFound=$(ls $fileTarget)

case ${filesFound} in
  "" ) printf "NO files found for target=${fileTarget}\n" ;;
   * ) printf "FileTarget Files found=${filesFound}\n" ;;
esac

Test

fileTarget="*.html"  # Where I have some HTML documents in the current directory

FileTarget Files found=Baby21.html
baby22.html
charlie  22.html
charlie21.html
charlie22.html
charlie23.html

fileTarget="xorg-x11-fonts*"

NO files found for target=xorg-x11-fonts*

注意,这只适用于当前目录,或者变量fileTarget包含您想要检查的路径的地方。

其他回答

PowerShell对通配符的处理方式是不同的,你可以像下面这样把它放在引号里:

If (Test-Path "./output/test-pdf-docx/Text-Book-Part-I*"){
  Remove-Item -force -v -path ./output/test-pdf-docx/*.pdf
  Remove-Item -force -v -path ./output/test-pdf-docx/*.docx
}

我认为这是有帮助的,因为最初问题的概念涵盖了一般的“shell”,而不仅仅是Bash或Linux,也适用于有相同问题的PowerShell用户。

您还可以删除其他文件

if [ -e $( echo $1 | cut -d" " -f1 ) ] ; then
   ...
fi

Use:

files=(xorg-x11-fonts*)

if [ -e "${files[0]}" ];
then
    printf "BLAH"
fi

我用这个:

filescount=`ls xorg-x11-fonts* | awk 'END { print NR }'`  
if [ $filescount -gt 0 ]; then  
    blah  
fi

严格来说,如果你只想打印“Blah”,下面是解决方案:

find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 'BLAH' -quit

这里有另一种方法:

doesFirstFileExist(){
    test -e "$1"
}

if doesFirstFileExist xorg-x11-fonts*
then printf "BLAH"
fi

但我认为最优的是如下所示,因为它不会尝试对文件名进行排序:

if [ -z $(find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit) ]
then 
     printf "BLAH"
fi