写一个shell /app使用超过80% 删除100个最久的 /app/pge17/backups/archive下的00000开头的文件
执行时加上日期
执行时加上清理的文件名字
#!/bin/bash
# Define the monitored mount point and the target backup directory
TARGET_DIR="/app/pge17/backups/archive"
THRESHOLD=80
# Function to print log messages with the current timestamp
log_msg() {
echo "$(date '+[%Y-%m-%d %H:%M:%S]') $1"
}
# 1. Get the current disk usage percentage of the /app partition (extract numbers only)
USAGE=$(df -h | awk '$NF=="/app"{sub(/%/,"",$5); print $5}')
# If matching by mount point fails, fallback to path-based matching
if [ -z "$USAGE" ]; then
USAGE=$(df -h "$TARGET_DIR" | awk 'NR==2{sub(/%/,"",$5); print $5}')
fi
# 2. Check if the disk usage exceeds the threshold
if [ "$USAGE" -gt "$THRESHOLD" ]; then
log_msg "WARNING: /app disk usage has reached ${USAGE}%, exceeding the threshold of ${THRESHOLD}%!"
# 3. Verify if the target directory exists
if [ -d "$TARGET_DIR" ]; then
log_msg "Scanning for the 100 oldest files starting with '00000' in ${TARGET_DIR}..."
# Get the list of the top 100 oldest files and store them in a temporary variable
# Using IFS= read -r to handle files properly
FILE_LIST=$(find "$TARGET_DIR" -maxdepth 1 -type f -name "00000*" -printf '%T+ %p\n' 2>/dev/null | sort | head -n 100 | cut -d' ' -f2-)
# Check if any matching files were found
if [ -n "$FILE_LIST" ]; then
log_msg "The following files will be deleted:"
# Print each file name with a timestamp
echo "$FILE_LIST" | while read -r file; do
log_msg "Removing file: $file"
done
# Perform the actual deletion
echo "$FILE_LIST" | xargs -r rm -f
log_msg "Cleanup completed successfully."
else
log_msg "No files starting with '00000' were found to delete."
fi
else
log_msg "ERROR: Target directory ${TARGET_DIR} does not exist!"
fi
else
log_msg "/app disk usage is normal (${USAGE}%), no cleanup needed."
fi
*/5 * * * * /app/scripts/delarch.sh >>/app/scripts/delarch.log 2>&1
/app/scripts/delarch.log 被删除后执行不了如何处理
为了防止以后日志文件再次被误删导致任务失败,你可以直接在 delarch.sh脚本的最开头( #!/bin/bash**下方)**加上这行代码:
bash
# Auto-create the log file if it was deleted
touch "/app/scripts/delarch.log" 2>/dev/null