检查文件夹是否包含glob

时间:2017-04-13 22:19:22

标签: bash macos shell

在我的Mac上,我试图找出一种方法来检查已安装的卷到服务器,以查看目录是否通过shell脚本接收日志文件,该脚本将在launchd中设置为时间间隔

从我的搜索和历史上我已经使用过:

$DIR="/path/to/file"
THEFILES=(`find ./ -maxdepth 1 -name "*.log"`)
if [ ${#THEFILES[@]} -gt 0 ]; then 
    echo "exists"
else
    echo "nothing"
fi

如果shell脚本放在该特定目录中并且文件存在。但是,当我将脚本移到该目录之外并尝试:

THEFILES=(`find ./ -maxdepth 1 -name "*.log"`)
cd $DIR
if [ ${#THEFILES[@]} -gt 0 ]; then 
    echo "exists"
else
    echo "nothing"
fi

我得到nothing的不断回报。我认为这可能与深度有关,所以我将-maxdepth 1更改为-maxdepth 0,但我仍然得到nothing。通过搜索我跑过" Check whether a certain file type/extension exists in directory"并试过:

THEFILES=$(ls "$DIR/.log" 2> /dev/null | wc -l)
echo $THEFILES

但是我返回了一个常量0。当我进一步搜索时,我跑过" Checking from shell script if a directory contains files"并尝试使用find进行变体:

THEFILES=$(find "$DIR" -type f -regex '*.log')
cd $DIR
if [ ${#THEFILES[@]} -gt 0 ]; then 
    echo "exists"
else
    echo "nothing"
fi

空白回报。当我尝试:

if [ -n "$(ls -A $DIR)" ]; then
    echo "exists"
else
    echo "nothing"
fi

我收到一个空白终端。在此answer我的Mac上没有pruneshopt。那么我如何检查已安装的服务器目录以查看是否存在具有特定扩展名的特定文件,该文件不会从隐藏文件中返回错误的内容?

编辑:

根据评论我尝试删除深度:

THEFILES=$(find ./ -name "*.log")

但是我得到一个空白的回报,但是如果我在那里放了一个.log文件,那么它就会运行,但我不明白为什么其他人不会返回nothing,除非它'考虑隐藏文件。感谢l'L'l我在-prune的实用程序中了解到find,但是当我尝试时:

if [ -n "$(find $DIR -prune -empty -type d)" ]; then

当存在LOG文件时,我得到nothing的常量返回。

2 个答案:

答案 0 :(得分:2)

Bash内置compgen"根据选项显示可能的完成情况"并且是typically used for autocomplete scripts,但也可以用于此目的。默认情况下,它会输出完成列表,因此将其重定向到/dev/null

#!/bin/bash
dir=/some/log/dir
if compgen -G "$dir/*.log" > /dev/null; then
    # do stuff
fi

答案 1 :(得分:1)

你提出的每个答案都非常接近工作!

我没有使用-maxdepth选项,如果您只检查$DIR下的文件而不是其子目录,请随意添加-maxdepth 1任何对find的调用。

使用 mklement0 指示的小写变量,以避免与环境变量发生冲突。

答案1

您设置dir,但使用./代替......

dir="/path/to/dir"
# Create an array of filenames
files=( $(find "$dir" -name "*.log") )
if [ ${#files[@]} -gt 0 ]; then # if the length of the array is more than 0
    echo "exists"
else
    echo "nothing"

答案2

运行find ...

后使用cd $dir
dir="path/to/dir"
cd "$dir"
files=( $(find -name "*.log") )
if [ ${#files[@]} -gt 0 ]; then
    echo "exists"
else
    echo "nothing"
fi

答案3

你忘记了' *'在' .log'之前看一下globbing

的文档
dir="/path/to/dir"
# print all the files in "$DIR" that end with ".log"
# and count the number of lines
nbfiles=$(ls "$dir/"*.log 2> /dev/null | wc -l) # nbfiles is an integer
if [ $nbfiles -gt 0 ]; then
    echo "exists"
else
    echo "nothing
fi

答案4

find的macOS手册页建议正则表达式默认使用Basic Regular Expressions:

  

-E

     

解释正则表达式,后跟-regex和-iregex          选项作为扩展(现代)正则表达式而不是          基本正则表达式(BRE' s)。

.之前您遗漏了*;由于您将cd $dir作为参数传递给查找,因此$dir没有必要;并且您不会将find的输出存储在数组中,因此您无法检查数组的长度。

# The output of find is stored as a string
files=$(find "/path/to/dir" -type f -regex '.*\.log')
if [ -n "$files" ]; then # Test that the string $files is not empty
    echo "exists"
else
    echo "nothing"
fi
相关问题