Unfortunately, because file names can have new line characters in them, find is highly limited command, which is hard to use right. To improve things over what you are doing now you cod do:
Code:
find /root/* -maxdepth 1 -type d -mtime +90 | while read DIR; do
…
done
but the problem with new line characters remains.
Second of all, always quote your variables. It's not always required, but if you are unsure, quote it.
Furthermore, $(…) is preferred over backtics. And lastly, you should clean up .tgz file if tar command fails. Lastly, tar's return code can be used to determine whether you need to remove the directory.
An as for counting number of files inside of a directory, find works better than ls -lR.
Code:
if ! [ -f "$DIR.tgz" ] &&
[ "$(find "$DIR" -type f -printf \\n | wc -l)" -gt 1000 ]; then
if tar czf "$DIR.tgz" "$DIR"; then
rm -r "$DIR"
else
rm -f "$DIR.tgz"
fi
fi
To solve problem with new lines in directory names pointed out at the beginning, the easiest way is to create another command for dealing with a directories, eg.:
blah.sh:
Code:
find /root/* -maxdepth 1 -type d -mtime +90 -exec sh blah-helper.sh {} +
blah-helper.sh:
If you don't have GNU find, replace “+” at the end of the find with “\;”.