I want to write a script that will clean backup directory from old files, leaving only latest N there. I also want to do it without using ls
.
Yesterday I ended up with the following piece of code:
counter=0
while IFS=/ read -rd '' time file; do
((counter++ < ${KEEP_NUMBER:?})) && continue
rm -f "$file"
done < <(find . -maxdepth 1 -type f -printf "%T@/%p\0" | sort -znr)
开发者_如何学PythonHowever, this isn't portable at all, as there is find -printf
been used, leaving behind all the boxes without GNU extensions.
Are there any better ways to accomplish such a task?
It can be done relatively easily provided you have
- A shell that supports arrays (as
bash
does) - Access to
test
(which can compare the age of 2 files)
Here's my attempt (it probably doesn't cope with spaces in filenames, but that could be fixed easily enough
#!/bin/bash
declare -a files
for file in *
do
files[${#files[@]}]=$file
done
# Bubble sort the files from newest to oldest
declare -i i j count=${#files[@]}
while true
do
declare -i sorted=1
for ((i=1;i<count;i++))
do
let j=i-1
if [ ${files[$j]} -ot ${files[$i]} ]
then
sorted=0
f=${files[$j]}
files[$j]=${files[$i]}
files[$i]=$f
fi
done
[ $sorted -eq 1 ] && break
done
# Delete everything except the first 5 files
for ((i=5;i<count;i++))
do
rm "${files[$i]}"
done
Well, there's POSIX -newer
primary to the find
. It - with some minor coding - can be used to separate files by their modification time. I would have done something like taking the first file, finding the ones newer. There i have two sets - newer and older. If there are more newer files than N, i repeat the process for the newer set only, otherwise i remember the newer set, subtract this number from N and repeat the process for the older set.
Or you can use pax
to create an archive, and then use -o listopt
to extract modification time in the format you want, there you have all the information:)
http://www.google.fr/search?q=zfs
else ...
man rsnapshoot
else ...
Stop trying to reinvent a backup suite
else ...
man find | grep -- -ctime man find | grep -- -delete
精彩评论