LifeSaver
LifeSaver

Reputation: 148

deleting 10 days old folder in linux

#!/bin/bash
now=$(date +"%d-%m-%Y")
year=$(date +"%Y")
echo $year
find  /var/backup/backup-scripts -name '*$year*' -ctime +10 -exec rm {} \;
~
~

This script is running with no errors but not removing 10 days old folder

Please advise

Thanks in anticipation

Upvotes: 1

Views: 530

Answers (2)

Adam Katz
Adam Katz

Reputation: 16138

@shellter's answer is a more direct mapping to your methodology, but here's how I would code that:

find  /var/backup/backup-scripts -name "*$(date +%Y)*" -mtime +10 -type f \
  -print0 |xargs -0 rm -v

Some differences:

  • It's a one-liner (though if you want a cron job, make a script)
  • -mtime ("modified") replaces -ctime ("changed") because sometimes access is a change
  • I restricted the results to files
  • I passed the output to xargs (in a manner safe for spaced filenames) to distribute the task

xargs is useful because it won't be overwhelmed by too many files (you can only send so many arguments to a command line program). It also runs slightly faster since it will run its multiple instances in parallel. (If it doesn't run multiple instances, there won't be any speedup, but in that case it probably won't take too long either way.)

One of the main reasons to use pipes here is that you can edit the output even further. Let's say you wanted to keep anything from January:

find /var/backup/backup-scripts -name "*$(date +%Y)*" -mtime +10 -type f \
  |egrep -v "$(date +%Y)-?01" |xargs -d "\n" rm -v

egrep -v will only show lines that do not match the given regex, so they won't be removed.

This uses \n as a delimiter rather than \0 (null), which will trip over files with line breaks in their names (don't do that!), but otherwise it excludes hits like file20150101.txt and file2015-01-01.txt (note the question mark in my extended posix regex; further explanation at regex101)

Upvotes: 1

shellter
shellter

Reputation: 37268

you're single quoting a variable, it can't be expanded by the shell. Try

find  /var/backup/backup-scripts -name "*$year*" -ctime +10 -exec rm {} \;

IHTH

Upvotes: 1

Related Questions