Link to home
Start Free TrialLog in
Avatar of nwaltham
nwaltham

asked on

Shell script to compare and delete files

I have two trees under the directories

/usr

and

/bak/usr

I would like to use a command or a short bash script that will
delete everything under /bak/usr which exists and has the same
date and relative path as a file under /usr. How would I do this?

Thanks in advance,
Nicholas Waltham
ASKER CERTIFIED SOLUTION
Avatar of mlev
mlev

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nwaltham
nwaltham

ASKER

Hello - thanks for your script. Its possible /bak/usr could have newer files, since its from a different system. I guess the modification to the script would only need to be slight...
You can make the 7th line read
  if [ -e "$bakfile" -a ! "$file" -nt "$bakfile" -a ! "$file" -ot "$bakfile" ]
but then identical directories won't be removed, since their date will change as their contents are removed. To solve this:

#!/bin/sh

find /usr -depth |
while read file
do
  bakfile="/bak$file"
  if [ -e "$bakfile" -a ! "$file" -nt "$bakfile" -a ! "$file" -ot "$bakfile" ]
  then
    echo "$bakfile"
  fi
done |
while read bakfile
do
  if [ -d "$bakfile" ]
  then
    rmdir "$bakfile" 2>/dev/null
  else
    rm -f "$bakfile"
  fi
done

Please note that even this way, in some cases directories still won't be removed e.g. because their date changed last time you ran this script. Maybe you should think of a different criterion for directories than date (e.g. empty and exist in both /bak/usr and /usr)

Thanks for your help!