Bash Script to Archive Old Files Easily
find /path/to/files -type f -mtime +N -print0 | tar -czvf archive.tar.gz --null -T - to archive files older than N days into a compressed tar file.Examples
How to Think About It
find with -mtime. Then, pass these files safely to tar to create a compressed archive. This avoids errors with spaces or special characters in filenames.Algorithm
Code
#!/bin/bash DIR="$1" DAYS="$2" ARCHIVE="archive.tar.gz" if [[ -z "$DIR" || -z "$DAYS" ]]; then echo "Usage: $0 <directory> <days>" exit 1 fi find "$DIR" -type f -mtime +$DAYS -print0 | tar -czvf "$ARCHIVE" --null -T - echo "Archived files older than $DAYS days from $DIR into $ARCHIVE"
Dry Run
Let's trace archiving files older than 7 days in /tmp/logs through the code
Check inputs
DIR=/tmp/logs, DAYS=7
Find old files
find /tmp/logs -type f -mtime +7 -print0 lists files older than 7 days
Create archive
tar reads file list from find and creates archive.tar.gz
| Step | Command | Result |
|---|---|---|
| 1 | Check inputs | DIR=/tmp/logs, DAYS=7 |
| 2 | find /tmp/logs -type f -mtime +7 -print0 | List of old files with null separator |
| 3 | tar -czvf archive.tar.gz --null -T - | archive.tar.gz created with old files |
Why This Works
Step 1: Finding old files
The find command with -mtime +N selects files modified more than N days ago.
Step 2: Handling filenames safely
Using -print0 with find and --null -T - with tar safely handles filenames with spaces or special characters.
Step 3: Creating compressed archive
The tar -czvf command creates a gzip compressed archive including the selected files.
Alternative Approaches
#!/bin/bash DIR="$1" DAYS="$2" ARCHIVE="archive.zip" if [[ -z "$DIR" || -z "$DAYS" ]]; then echo "Usage: $0 <directory> <days>" exit 1 fi find "$DIR" -type f -mtime +$DAYS -print | zip "$ARCHIVE" -@ echo "Archived files older than $DAYS days from $DIR into $ARCHIVE"
#!/bin/bash DIR="$1" DAYS="$2" ARCHIVE_DIR="$DIR/archive_$(date +%Y%m%d)" if [[ -z "$DIR" || -z "$DAYS" ]]; then echo "Usage: $0 <directory> <days>" exit 1 fi mkdir -p "$ARCHIVE_DIR" find "$DIR" -type f -mtime +$DAYS -exec mv {} "$ARCHIVE_DIR" \; echo "Moved files older than $DAYS days to $ARCHIVE_DIR"
Complexity: O(n) time, O(1) space
Time Complexity
The script scans all files once with find, so time grows linearly with number of files.
Space Complexity
No extra memory is used proportional to input size; files are processed in stream.
Which Approach is Fastest?
Using tar with find is efficient; zip may be slower for many files, moving files is fast but changes file locations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| find + tar | O(n) | O(1) | Safe archiving with compression |
| find + zip | O(n) | O(1) | Windows-friendly archives |
| find + move | O(n) | O(1) | Freeing space by relocating files |
-print0 and --null options.