#! /bin/bash
RemoteUser=root
RemoteIP=192.168.XXX.XXX
# 远程备份服务器存放路径
RemoteBackupDir=/home/backups
#日志输出目录
BackupLog=/var/opt/logs/backup.log
if [ $? -eq 0 ]; then
# 获取远程备份列表
ssh "$RemoteUser@$RemoteIP" "find '$RemoteBackupDir' -type f -name '*.tar' -exec stat -c '%Y %n' {} \; | sort -n" > $RemoteBackupList
SevenDaysAgo=$(date -d '7 days ago' +%s)
# 删除超过7天的备份
while IFS= read -r line || [[ -n $line ]]; do
echo "进入循环>>>>" >> $BackupLog
modtime_seconds=$(echo "$line" | awk '{print $1}')
filepath=$(echo "$line" | awk '{print $2}')
if (( modtime_seconds < SevenDaysAgo )); then
# 注释ssh语句 进入循环就能打印多次, 放开就只打印一次
ssh "$RemoteUser@$RemoteIP" "rm -f '$filepath'" >> $BackupLog 2>&1
if [ $? -ne 0 ]; then
echo "删除远程旧备份失败: $filepath" >> $BackupLog
fi
fi
done < "$RemoteBackupList"
# 清理临时文件
rm -f "$RemoteBackupList"
else
echo ">>>>>远程备份失败>>>>>>$(date +"%Y-%m-%d %H:%M:%S")" >> $BackupLog
fi
问题是:只要注释ssh "$RemoteUser@$RemoteIP" "rm -f '$filepath'" >> $BackupLog 2>&1
这条语句,echo "进入循环>>>>" >> $BackupLog
就能多次打印, 一旦放开就只执行一次,也没有任何报错; 现象就是只删除了1个符合条件的文件,其余的都没删掉;$RemoteBackupList
也没有啥问题,格式就是下面的
1726239998 /home/1726066986_2024_09_11_14.6.1_test_backup.tar
1728871975 /home/1728831723_2024_10_13_14.6.1_test_backup.tar
1728885726 /home/1728871651_2024_10_14_14.6.1_test_backup.tar
1728894007 /home/1728885455_2024_10_14_14.6.1_test_backup.tar
1728895145 /home/1728894838_2024_10_14_14.6.1_test_backup.tar
1728895857 /home/1728895569_2024_10_14_14.6.1_test_backup.tar
1728899038 /home/1728898757_2024_10_14_14.6.1_test_backup.tar
...省略号代替...
虽然最后改用了find xxx -exec
,没用while
,但还是想知道while
这里有什么问题