我试图检查一个文件是否存在,但与通配符。以下是我的例子:
if [ -f "xorg-x11-fonts*" ]; then
printf "BLAH"
fi
我也试过不加双引号。
我试图检查一个文件是否存在,但与通配符。以下是我的例子:
if [ -f "xorg-x11-fonts*" ]; then
printf "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
其他回答
人测试。
if [ -e file ]; then
...
fi
将工作目录和文件。
恕我直言,最好在测试文件、glob或目录时使用find always。这样做的绊脚石是find的退出状态:如果成功遍历所有路径,则为0,否则为>。传递给find的表达式在退出代码中没有创建回显。
下面的示例测试目录是否有条目:
$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty
当A没有文件时,grep失败:
$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty
当A不存在时,grep再次失败,因为查找只打印到stderr:
$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty
用其他find表达式替换-not -empty,但如果-exec命令打印到stdout,请小心。在这种情况下,您可能需要使用grep来获得更具体的表达式。
这种方法在shell脚本中工作得很好。最初的问题是寻找glob xorg-x11-fonts*:
if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
: the glob matched
else
: ...not
fi
注意,如果xorg-x11-fonts*没有匹配,或者find遇到错误,就会到达else-branched。使用$?来区分大小写。
在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。我很高兴我没有踩进去;)
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 [ -n "$(find somedir/that_may_not_exist_yet -maxdepth 1 -name \*.ext -print -quit)" ] ; then
echo Such file exists
fi