【发布时间】:2017-04-13 22:19:21
【问题描述】:
在我的 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 上没有prune 或shopt。那么如何检查已安装服务器的目录以查看是否存在具有特定扩展名且不会从隐藏文件中返回错误的特定文件?
编辑:
根据评论,我尝试删除深度:
THEFILES=$(find ./ -name "*.log")
但我得到一个空白返回,但如果我将 .log 文件放在那里,它会运行,但我不明白为什么 else 不返回 nothing,除非它正在考虑隐藏文件。感谢l'L'l,我了解到-prune 在find 的实用程序中,但是当我尝试时:
if [ -n "$(find $DIR -prune -empty -type d)" ]; then
当存在 LOG 文件时,我会不断返回 nothing。
【问题讨论】:
-
您正在使用
-maxdepth限制命令遍历的距离;听起来这可能是问题所在。此外,prune包含在 Mac 的find实用程序中... -
这个
find ./ -maxdepth 1 -name "*.log从当前目录(脚本所在的位置)搜索。如果你把它移到外面,当然,它是行不通的。使用完整路径名,例如find /full/path/name/to/dir -maxdepth.... etc -
也许可以试试
find "$DIR" -name "*.log" | wc -l。您的许多命令都在抑制输出,或者以不会返回任何内容的方式进行设置。 -
我无法确定您要查找的内容。你有目录,你只想看看
*.log是否存在于该目录中? -
@miken32 是正确的。每隔 5 分钟通过一个应用程序,我想检查目录中是否存在日志文件。