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
- How would you write a health-check script that polls a URL until it returns 200? [Advanced]
- What is the difference between a cron job and a systemd timer? [Advanced]
- What is idempotency, and how do you make a script safe to run repeatedly? [Advanced]
- What is the difference between sed -i and sed without -i? [Advanced]
- How do you securely handle secrets in a shell script (avoid hardcoding, use env or a vault)? [Advanced]
- How do you use awk to sum or average a column? [Advanced]
- What is the difference between NR and NF in awk? [Advanced]
- How do you define and call a function (or step) in a Jenkins Groovy pipeline? [Advanced]