为什么在shell中检查文件是否存在总是false



我使用bash创建了一个cron来删除超过3天的文件,但在使用mtime+3&gt/dev/null它总是false。这是脚本:

now=$(date)
create log file
file_names=('*_takrib_golive.gz' '*_takrib_golive_filestore.tar.gz')
touch /media/nfs/backup/backup_delete.log
echo "Date: $now" >> /media/nfs/backup/backup_delete.log
for filename in "${file_names[@]}";
do
echo $filename
if ls /media/nfs/backup/${filename} &> /dev/null
then
echo "backup files exist"
if find /media/nfs/backup -maxdepth 1 -mtime +3 -name ${filename} -ls &> /dev/null
then
echo "The following backup file was deleted" >> /media/nfs/backup/backup_delete.log 
find /media/nfs/backup -maxdepth 1 -mtime +3 -name ${filename} -delete
else
echo "There are no ${filename} files older than 3 days in /media/nfs/backup" &>> /media/nfs/backup/backup_delete.log
fi
else
echo "No ${filename} files found in /media/nfs/backup" >> /media/backup/backup_delete.log
fi
done
exit 0

if find /media/nfs/backup -maxdepth 1 -mtime +3 -name ${filename} -ls &> /dev/null中,即使目录中存在超过3天的文件,也总是转到else

您没有引用-name属性,因此它扩展到已经存在的文件的名称。

无论如何,我都会对其进行相当广泛的重构。不要解析ls输出,也许可以通过更清楚地说明何时报价和何时不报价来简化它。

未经测试,但希望仍然有点用处:

#!/bin/bash
backup=/media/nfs/backup
backuplog=$backup/backup_delete.log
# no need to touch if you write to the file anyway
date +"Date: %C" >> "$backuplog"
# Avoid using a variable, just loop over the stems
for stem in takrib_golive takrib_golive_filestore.tar
do
# echo $filename
# Avoid parsing ls; instead, loop over matches
for filename in "$backup"/*_"$stem".gz; do
pattern="*_$stem.gz"
if [ -e "$filename" ]; then
echo "backup files exist"
if files=$(find "$backup" -maxdepth 1 -mtime +3 -false -o -name "$pattern" -print -delete)
then
echo "The following backup file was deleted" >> "$backuplog"
echo "$files" >> "$backuplog"
else
echo "There are no $pattern files older than 3 days in $backup" >> "$backuplog"
fi
else
echo "No $pattern files found in $backup" >> "$backuplog"
fi
# Either way, we can break the loop after one iteration
break
done
done
# no need to explicitly exit 0

for+if [ -e ... ]的排列有点笨拙,但这就是检查通配符是否与任何文件匹配的方式。如果通配符不匹配,if [ -e将检查名称实际上是通配符表达式本身的文件,但失败。

相关内容

  • 没有找到相关文章

最新更新