我试图检查一个文件是否存在,但与通配符。以下是我的例子:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
我也试过不加双引号。
我试图检查一个文件是否存在,但与通配符。以下是我的例子:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
我也试过不加双引号。
当前回答
人测试。
if [ -e file ]; then
...
fi
将工作目录和文件。
其他回答
您可以执行以下操作:
set -- xorg-x11-fonts*
if [ -f "$1" ]; then
printf "BLAH"
fi
这适用于sh和衍生品:KornShell和Bash。它不会创建任何子壳。$(..)和'…在其他解决方案中使用的命令会创建一个子shell:它们会派生一个进程,而且效率很低。当然,它可以处理多个文件,而且这个解决方案可能是最快的,或者仅次于最快的。
当没有任何匹配时,它也能工作。没有必要像某位评论员所说的那样使用nullglob。$1将包含原始的测试名称,因此test -f $1将不会成功,因为$1文件不存在。
解决方案:
files=$(ls xorg-x11-fonts* 2> /dev/null | wc -l)
if [ "$files" != "0" ]
then
echo "Exists"
else
echo "None found."
fi
> Exists
在KornShell, Bash和Z shell shell中使用新的花哨的shmancy特性(这个例子不处理文件名中的空格):
# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}
# Not found if the first element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
echo "No files not found"
elif [ $array_length -eq 1 ] ; then
echo "File was found"
else
echo "Files were found"
fi
for myfile in ${myarray[@]}
do
echo "$myfile"
done
是的,这闻起来确实像Perl。我很高兴我没有踩进去;)
Use:
if [ "`echo xorg-x11-fonts*`" != "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
我发现了一些值得分享的巧妙解决方案。第一个仍然存在“如果匹配太多就会破坏”的问题:
pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"
(回想一下,如果你使用一个没有[]语法的数组,你会得到数组的第一个元素。)
如果你在你的脚本中有"shop -s nullglob",你可以简单地这样做:
matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"
现在,如果一个目录中可能有大量的文件,你很可能会使用find:
find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'