Вопрос

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 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.

Это было полезно?

Решение 2

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

Другие советы

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top