@@ -103,7 +103,7 @@ compare_partition_space() {
103
103
# Help function
104
104
help () {
105
105
cat << EOF
106
- $0 - Backup script to create and restore backups [version: 1.0 .0]
106
+ $0 - Backup script to create and restore backups [version: 1.1 .0]
107
107
108
108
$0 [MODE][OPTIONS]
109
109
@@ -118,6 +118,7 @@ $0 [MODE][OPTIONS]
118
118
-b Backup directory
119
119
-v Verify backup after creation
120
120
-l [PATH/NAME] Log file to write the output (default: backup.log)
121
+ -k [NUMBER] Number of backups to keep (latest backups)
121
122
122
123
Restore options:
123
124
-b Backup directory
@@ -127,6 +128,7 @@ $0 [MODE][OPTIONS]
127
128
Examples:
128
129
$0 -c # Create backup in the default directory
129
130
$0 -c -v # Verify backup after creation
131
+ $0 -c -k 3 -v # Keep the latest 3 backups and verify
130
132
$0 -c -s /path/to/source # Create backup of a specific directory
131
133
$0 -c -b /path/to/backup # Create backup in a specific directory
132
134
$0 -c -s /path/to/source -b /path/to/backup
@@ -191,6 +193,31 @@ verify_backup() {
191
193
fi
192
194
}
193
195
196
+ # Function to remove old backup archives
197
+ remove_old_backups () {
198
+ # Number of backups to keep
199
+ local keep=$1
200
+
201
+ if [ ! -d " $BACKUP_DIR " ]; then
202
+ logger " ERROR: Backup directory $BACKUP_DIR does not exist." >&2
203
+ exit 1
204
+ fi
205
+
206
+ # Get a list of all backup files, sorted by date
207
+ mapfile -t backups < <( find " $BACKUP_DIR " -name " ${BACKUP_PREFIX} *.tar.gz" -exec basename {} \; | sort -r)
208
+
209
+ if [ ${# backups[@]} -le " $keep " ]; then
210
+ logger " INFO: No old backup files to remove." >&2
211
+ return 0
212
+ fi
213
+
214
+ # Remove all backup files that are older than the specified number
215
+ for (( i= keep; i< ${# backups[@]} ; i++ )) ; do
216
+ rm " $BACKUP_DIR /${backups[$i]} "
217
+ logger " INFO: Removed old backup ${backups[$i]} "
218
+ done
219
+ }
220
+
194
221
# ##############################################################################
195
222
# RESTORE BACKUP FUNCTIONS #
196
223
# ##############################################################################
@@ -272,8 +299,9 @@ main() {
272
299
;;
273
300
-c|--create)
274
301
VERIFY=false
302
+ KEEP=0
275
303
shift
276
- while getopts " :s:b:vl:" opt; do
304
+ while getopts " :s:b:vl:k: " opt; do
277
305
case ${opt} in
278
306
s )
279
307
SOURCE_DIR=$OPTARG
@@ -287,6 +315,9 @@ main() {
287
315
l )
288
316
LOG_FILE=$OPTARG
289
317
;;
318
+ k )
319
+ KEEP=$OPTARG
320
+ ;;
290
321
\? )
291
322
error " Invalid option: -$OPTARG "
292
323
;;
@@ -303,6 +334,10 @@ main() {
303
334
if [ " $VERIFY " = true ]; then
304
335
verify_backup
305
336
fi
337
+ # If the keep option was specified, remove old backups
338
+ if [ " $KEEP " -gt 0 ]; then
339
+ remove_old_backups " $KEEP "
340
+ fi
306
341
logger " Done!"
307
342
exit 0
308
343
;;
0 commit comments