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 --
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
- What is the purpose of the shebang line, and what does #!/bin/bash do? [Basic]
- What is the difference between sh and bash? [Basic]
- How do you make a script executable and run it? [Basic]
- What is the difference between running a script with ./script.sh, bash script.sh, and source script.sh? [Basic]
- What does sourcing a script do differently from executing it? [Basic]
- How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
- What is the difference between $var and ${var}? [Basic]
- What is the difference between single quotes and double quotes in Bash? [Basic]