Interview Scripting (Bash, Groovy)

How would you write a backup script that rotates and keeps only the newest N files? [Advanced]

Answer

A backup rotation script should create a timestamped backup, verify it exists and is non-empty, then delete older backups while keeping the newest N. Sorting by modification time or timestamped names makes retention deterministic.

Technical explanation

Write backups to a temporary file first, then move into place after success to avoid retaining partial backups.

Use find or ls carefully; for robust handling, use null delimiters when filenames can contain spaces.

Retention should be based on business requirements and ideally paired with restore tests.

Hands-on example

#!/usr/bin/env bash

set -euo pipefail

backup_dir=/var/backups/app

keep=7

mkdir -p "$backup_dir"

file="$backup_dir/app-$(date +%Y%m%d-%H%M%S).tar.gz"

tar -czf "$file.tmp" /opt/app

mv "$file.tmp" "$file"

find "$backup_dir" -maxdepth 1 -name 'app-*.tar.gz' -printf '%T@ %p\0' |

sort -z -rn |

tail -z -n +$((keep + 1)) |

cut -z -d' ' -f2- |

xargs -0 -r rm --

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Scripting (Bash, Groovy) interview questions

← All Scripting (Bash, Groovy) questions