I am using a small Bash script to periodically purge old backups:
FILE_LIST=`mktemp --suffix=.list`
find . -maxdepth 1 -type d -mtime +30 -print0 > $FILE_LIST
xargs --no-run-if-empty --null --arg-file $FILE_LIST rm -rvf
rm -f $FILE_LIST
The problem, however, is that files are not guaranteed to be user-writable, so rm
may fail to delete them. I need therefore to run chmod
before rm
in order to change its permissions:
xargs --no-run-if-empty --null --arg-file $FILE_LIST chmod -vR 700
But this is inefficient, as it calls chmod
on all the files in the found directories, when the vast majority of them probably don not need to be chmoded. Ideally, I would want to call find
again, this time with ! -perm -u+w
! -perm -u+w
and searching only in the directories contained in $FILE_LIST
.
What would be the best way to achieve this? I am basically looking for something to replicate the functionality of xargs
's --arg-file
option.
find . -maxdepth 1 -type d -mtime +30 -writable -exec rm -rf {} \;
and then
find . -maxdepth 1 -type d -mtime +30 -exec chmod u+w {} \; -exec rm -rf {} \;
I hope this solves the purpose
There is a way to do it — we can chain xargs
- find
- xargs
- chmod
:
# Find unwritable files and chmod them
xargs -I {} -0r -a $FILE_LIST find {} ! -perm -u+w -print0 | xargs -0r chmod -R 700 -v
The full Bash script, thus, would be:
FILE_LIST=`mktemp --suffix=.list`
find ~/udit65_backup/ -maxdepth 1 -iname "$PREFIX-*" -type d -mtime +$NDAYS -print0 > $FILE_LIST
# Make unwritable files... writable
xargs -I {} -0r -a $FILE_LIST find {} ! -perm -u+w -print0 | xargs -0r chmod -R 700 -v
xargs -0r -a $FILE_LIST rm -rf -v
rm -f $FILE_LIST
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.