Simple backup-remove.sh

Simple script to keep given amount of example backup files and remove the rest:

#!/bin/bash

if [ "$3" == "" ]; then
 echo "Usage: backup-remove.sh <directory> <amount-of-backups-to-keep> <backup-file-prefix> [test]"
 exit 1
fi

directory="$1"
amount="$2"
prefix="$3"
testonly="$4"

# set internal field separator for if loop to only new line
IFS=$'\n'

if [ ! -d "$directory" ]; then
 echo "Directory $directory does not exist"
 exit 1
fi
cd "$directory"

files_sorted=`ls -txd1 "$prefix"*`
if [ "$?" != "0" ]; then
 echo "Listing directory $directory contents failed"
 exit 1
fi

files=""
i=0
for file in $files_sorted; do
 i=$((i+1))
 if [ "$i" -gt "$amount" ]; then
 files=$files$'\n'$file
 fi
done

for file in $files; do
 if [ "$testonly" == "test" ]; then
 echo "$file"
 else
 rm -rf "$file"
 fi
done

# clear IFS
unset IFS

Leave a Reply

Your email address will not be published. Required fields are marked *