我试图检查一个文件是否存在,但与通配符。以下是我的例子:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
我也试过不加双引号。
我试图检查一个文件是否存在,但与通配符。以下是我的例子:
if [ -f "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'
其他回答
我发现了一些值得分享的巧妙解决方案。第一个仍然存在“如果匹配太多就会破坏”的问题:
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'
我使用的Bash代码:
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
for i in xorg-x11-fonts*; do
if [ -f "$i" ]; then printf "BLAH"; fi
done
这将适用于多个文件,文件名中有空白。
在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。我很高兴我没有踩进去;)
如果网络文件夹中有大量文件,使用通配符是有问题的(速度,或命令行参数溢出)。
最后我得到了:
if [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name \*.ext -print -quit)" ] ; then
echo Such file exists
fi