Delete files older than 10 days using shell script

2019-01-04 17:09发布

This question already has an answer here:

I'm new to shell scripts, can anyone help? I want to delete scripts in a folder from the current date back to 10 days. The scripts looks like:

2012.11.21.09_33_52.script
2012.11.21.09_33_56.script
2012.11.21.09_33_59.script

The script will run in every 10 day with Crontab, that's why I need the current date.

3条回答
Emotional °昔
2楼-- · 2019-01-04 17:12

If you can afford working via the file data, you can do

find -mmin +14400 -delete
查看更多
Evening l夕情丶
3楼-- · 2019-01-04 17:32

find is the common tool for this kind of task :

find ./my_dir -mtime +10 -type f -delete

EXPLANATIONS

  • ./my_dir your directory (replace with your own)
  • -mtime +10 older than 10 days
  • -type f only files
  • -delete no surprise. Remove it to test your find filter before executing the whole command

And take care that ./my_dir exists to avoid bad surprises !

查看更多
不美不萌又怎样
4楼-- · 2019-01-04 17:38

Just spicing up the shell script to delete older files

#!/bin/bash

timestamp=$(date +%Y%m%d_%H%M%S)
path="/data/backuplog"
filename=log_back_$timestamp.txt
log=$path/$filename

find $path -name "*.txt"  -type f -mtime +7 -print -delete >> $log

echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log

START_TIME=$(date +%s)

... code for backup ...or any other operation ....


END_TIME=$(date +%s)

ELAPSED_TIME=$(expr $END_TIME - $START_TIME)


echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log
echo "Elapsed Time ::  $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) "  >> $log

The code build on sputnick's answer and adds a few more things.

  • log files named with a timestamp
  • log folder specified
  • find looks for *.txt files only in the log folder
  • log files older than 7 days are deleted ( assuming this is for a backup log)
  • notes the start / end time
  • calculates the elapsed time...
查看更多
登录 后发表回答