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

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

我也试过不加双引号。


当前回答

Use:

files=(xorg-x11-fonts*)

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

其他回答

您可以执行以下操作:

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

这适用于sh和衍生品:KornShell和Bash。它不会创建任何子壳。$(..)和'…在其他解决方案中使用的命令会创建一个子shell:它们会派生一个进程,而且效率很低。当然,它可以处理多个文件,而且这个解决方案可能是最快的,或者仅次于最快的。

当没有任何匹配时,它也能工作。没有必要像某位评论员所说的那样使用nullglob。$1将包含原始的测试名称,因此test -f $1将不会成功,因为$1文件不存在。

人测试。

if [ -e file ]; then
...
fi

将工作目录和文件。

Use:

if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
    printf "BLAH"
fi

解决方案:

files=$(ls xorg-x11-fonts* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
   echo "Exists"
else
    echo "None found."
fi

> Exists

试试这个

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包含您想要检查的路径的地方。