Bash Script to Compress Files Older Than N Days
find /path/to/files -type f -mtime +n -exec gzip {} \; in a Bash script to compress files older than n days, where n is the number of days.Examples
How to Think About It
find with the -mtime +n option, which selects files modified more than n days ago. Then, for each found file, run a compression command like gzip to compress it. This approach automates cleanup and saves space.Algorithm
Code
#!/bin/bash DIR="$1" DAYS="$2" if [[ -z "$DIR" || -z "$DAYS" ]]; then echo "Usage: $0 <directory> <days>" exit 1 fi find "$DIR" -type f -mtime +$DAYS -exec gzip {} \; -print
Dry Run
Let's trace compressing files older than 1 day in /tmp/testfiles.
Input parameters
DIR=/tmp/testfiles, DAYS=1
Find files older than 1 day
find /tmp/testfiles -type f -mtime +1
Compress each found file
gzip /tmp/testfiles/oldfile.txt
| File Found | Action |
|---|---|
| /tmp/testfiles/oldfile.txt | gzip /tmp/testfiles/oldfile.txt |
| /tmp/testfiles/oldlog.log | gzip /tmp/testfiles/oldlog.log |
Why This Works
Step 1: Finding old files
The find command with -mtime +n selects files modified more than n days ago.
Step 2: Compressing files
The -exec gzip {} \; runs gzip on each found file, compressing it in place.
Step 3: Printing compressed files
The -print option outputs the name of each compressed file for confirmation.
Alternative Approaches
#!/bin/bash DIR="$1" DAYS="$2" if [[ -z "$DIR" || -z "$DAYS" ]]; then echo "Usage: $0 <directory> <days>" exit 1 fi FILES=$(find "$DIR" -type f -mtime +$DAYS) if [[ -n "$FILES" ]]; then tar -czf old_files_$(date +%Y%m%d).tar.gz $FILES echo "Compressed files into old_files_$(date +%Y%m%d).tar.gz" else echo "No files older than $DAYS days found." fi
#!/bin/bash DIR="$1" DAYS="$2" if [[ -z "$DIR" || -z "$DAYS" ]]; then echo "Usage: $0 <directory> <days>" exit 1 fi find "$DIR" -type f -mtime +$DAYS -print0 | xargs -0 gzip find "$DIR" -type f -name '*.gz' -print
Complexity: O(n) time, O(1) space
Time Complexity
The script runs find once over all files, which is O(n) where n is the number of files. Each matching file is compressed individually, so total time depends on the number of old files.
Space Complexity
The script uses constant extra space, compressing files in place without storing large data in memory.
Which Approach is Fastest?
Using find -exec gzip compresses files one by one, while find | xargs gzip can be faster by batching. Archiving with tar compresses all files at once but requires extra disk space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| find -exec gzip | O(n) | O(1) | Simple per-file compression |
| find | xargs gzip | O(n) | O(1) | Faster batch compression |
| tar archive | O(n) | O(n) | Single archive of many files |
\; in the find -exec command causes syntax errors.