Automate Daily Unrar Extraction with a Cron Job

Automating RAR archive extraction on a daily schedule ensures that newly downloaded or updated compressed files are unpacked consistently without manual intervention. This guide outlines how to create a Bash script utilizing unrar to extract and sync your data, make the script executable, and schedule it as a daily automated task using Linux's cron utility.

Step 1: Install the Required Tools

Ensure unrar is installed on your Linux system.

On Debian/Ubuntu-based distributions:

sudo apt update
sudo apt install unrar

On RHEL/CentOS/Rocky Linux:

sudo dnf install epel-release
sudo dnf install unrar

Step 2: Create the Extraction Script

Running unrar directly via cron can lead to issues with file paths and error handling. Writing a dedicated shell script ensures archives are extracted cleanly and only new files are processed.

Create a script file:

nano /usr/local/bin/daily_unrar_sync.sh

Add the following script content:

#!/usr/bin/env bash

# Define source and destination directories
SOURCE_DIR="/path/to/rar_files"
DEST_DIR="/path/to/extracted_data"
LOG_FILE="/var/log/unrar_sync.log"

# Create destination and log directories if they do not exist
mkdir -p "$DEST_DIR"
mkdir -p "$(dirname "$LOG_FILE")"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting unrar sync..." >> "$LOG_FILE"

# Iterate over all .rar files in the source directory
for archive in "$SOURCE_DIR"/*.rar; do
    # Check if files matching the pattern exist
    [ -e "$archive" ] || continue

    # -x: Extract files with full path
    # -o-: Do not overwrite existing files (skips already extracted data)
    # -inul: Disable error messages to stdout
    unrar x -o- "$archive" "$DEST_DIR/" >> "$LOG_FILE" 2>&1
done

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Extraction completed." >> "$LOG_FILE"

The -o- switch ensures unrar skips files that already exist in the target directory, preventing redundant writes and keeping the extraction directory in sync with the source archives.

Step 3: Set Permissions

Make the script executable so the cron daemon can run it:

chmod +x /usr/local/bin/daily_unrar_sync.sh

Test the script manually to confirm it processes the files properly:

/usr/local/bin/daily_unrar_sync.sh

Check /var/log/unrar_sync.log to verify that the extraction executed without errors.

Step 4: Schedule the Cron Job

Open the crontab configuration for the user running the job:

crontab -e

Add a daily schedule entry. To run the script every day at 02:00 AM, append the following line:

0 2 * * * /usr/local/bin/daily_unrar_sync.sh >/dev/null 2>&1

Save and exit the editor. The cron service will automatically read the updated configuration and execute the extraction job every day at the specified time.