Check if a file exists with a wildcard in a shell script

Viewed 425310

I'm trying to check if a file exists, but with a wildcard. Here is my example:

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

I have also tried it without the double quotes.

21 Answers

Strictly speaking, if you only want to print "Blah", here is the solution:

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

Here is another way:

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

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

But I think the most optimal is as follows, because it won't try to sort file names:

if [ -z $(find . -maxdepth 1 -name 'xorg-x11-fonts*' -printf 1 -quit) ]
then 
     printf "BLAH"
fi
if [ `ls path1/* path2/* 2> /dev/null | wc -l` -ne 0 ]; then echo ok; else echo no; fi

You can also cut other files out

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