This script keep the last five files

# Archiving /path/to/name/pattern*.tar.gz
 
n=0
arch=5
for i in `ls -ltr backup.sql*.tar.gz | awk '{print $9}' | sort -r `
do
	n=`expr $n + 1`
	if [ $n -le $arch ]; then
		echo "Keep "$i
		continue
	fi
	echo "Delete "$i
	rm -f $i
done

Another example

archive_file()
{
	local arch=5
	local arch_pattern=$1
	
	if [ -n "$2" ]; then
		arch=$2
	fi
	
	ls -t $arch_pattern | tail -n +$(($arch+1)) | xargs rm -f 
}
 
archive_file "/tmp/backup*.sql.tar.gz"

TAGS : Tutorial Shell Unix archive recent files