How to Run 7-Zip Commands in Linux Cron Jobs
This guide explains how to automate file compression and backups by
running 7-Zip commands inside Linux cron jobs. You will learn how to
install 7-Zip, write a dependable shell script using absolute file paths
and dynamic timestamps, configure the proper execution permissions, and
schedule the automated task using the crontab editor.
Step 1: Install 7-Zip on Linux
Ensure the 7-Zip binary is installed on your Linux distribution.
On Debian or Ubuntu:
sudo apt update
sudo apt install 7zip(On older releases, install p7zip-full
instead.)
On RHEL, CentOS, or Fedora:
sudo dnf install epel-release -y
sudo dnf install p7zip p7zip-plugins -yVerify the installation and locate the absolute binary path:
which 7zCommon paths are /usr/bin/7z or /bin/7z.
Note this path, as cron requires absolute paths to function
reliably.
Step 2: Create a Backup Shell Script
While you can run 7-Zip directly inside crontab, wrapping the command in a shell script allows you to handle timestamps, multi-directory targets, and error logging much more cleanly.
Create a script file:
nano /usr/local/bin/cron_backup.shPaste the following script, replacing directories with your actual paths:
#!/bin/bash
# Configuration
BIN_7Z="/usr/bin/7z"
SRC_DIR="/var/www/html"
DEST_DIR="/backup"
DATE=$(date +"%Y-%m-%d_%H%M%S")
ARCHIVE_NAME="$DEST_DIR/backup_$DATE.7z"
# Ensure the backup directory exists
mkdir -p "$DEST_DIR"
# Execute 7-Zip compression
# -mx=9 sets ultra compression (optional, default is -mx=5)
# -p adds a password if needed (e.g., -p"SecretPassword")
$BIN_7Z a -mx=9 "$ARCHIVE_NAME" "$SRC_DIR" > /dev/null 2>&1Step 3: Set Execution Permissions
Make the script executable by root or the user running the cron job:
chmod +x /usr/local/bin/cron_backup.shTest the script manually to confirm it creates the archive without errors:
/usr/local/bin/cron_backup.shVerify that the .7z file was created in your destination
directory before scheduling it.
Step 4: Schedule the Script in Cron
Open the cron table editor for your user or root:
crontab -eAdd an entry specifying the time interval and the script path.
Example Schedules:
Run daily at 2:00 AM:
0 2 * * * /usr/local/bin/cron_backup.sh >> /var/log/7z_backup.log 2>&1Run every Sunday at midnight:
0 0 * * 0 /usr/local/bin/cron_backup.sh >> /var/log/7z_backup.log 2>&1Run every 6 hours:
0 */6 * * * /usr/local/bin/cron_backup.sh >> /var/log/7z_backup.log 2>&1
The >> /var/log/7z_backup.log 2>&1
directive appends all standard output and error messages to a log file,
which helps with troubleshooting if an archive operation fails. Save and
exit the editor; cron will immediately load the new schedule.