East4Serv Premium Header
E4S
East4Serv
LINUX CLOUD MAGENTO
Login
E4S
East4Serv
Blog About us Contact Support ترجمة للعربية (AR)
Link copied to clipboard!
🏠 Home / 📰 Insights Blog / Bulk Image Optimization & Safe Backup: F...

Bulk Image Optimization & Safe Backup: Free Linux Bash Script - East4Serv

📅 Mar 21, 2026 👁 26 Views
Share:
...

Free Linux Bash Script for Bulk Image Optimization & Safe Backup

Introduction

In today's fast-paced digital landscape, website speed is no longer just a luxury—it is a critical ranking factor for SEO and a cornerstone of user experience. One of the most common culprits behind slow page load times is unoptimized, oversized images. While there are many plugins and paid services available, System Administrators and developers often need a fast, reliable, and server-side solution to handle thousands of images at once.

That is why the team at East4Serv has developed a powerful, lightweight, and completely free Bash script to automate bulk image optimization on Linux servers. Our script not only compresses your JPG and PNG files without losing visible quality, but it also prioritizes your data safety by creating a structural backup before any modifications occur.

Why Use the East4Serv Image Optimizer?

When managing server infrastructure, running commands that modify files directly can be risky. Our script eliminates that risk. It is designed with the daily challenges of DevOps and System Administration in mind.

Key Features:

  • Automated Structural Backups: Before compressing a single file, the script prompts you for a backup directory. It perfectly mirrors your project's directory structure and copies the original images there, ensuring you always have a fallback.

  • In-Place Optimization: Images are compressed and saved with their exact original names and extensions. No broken links, no need to rewrite HTML or CSS paths.

  • Lossless & Smart Compression: Utilizing industry-standard tools, the script significantly reduces file sizes while stripping unnecessary metadata, maintaining the visual integrity of your assets.

  • 100% Free & Open-Source: No API limits, no subscription fees. Run it on your servers as often as you need.

Prerequisites

To ensure the script runs smoothly, you need to install two lightweight image processing packages on your Linux server.

Run the following commands based on your distribution:

For Debian/Ubuntu (APT):

sudo apt-get update
sudo apt-get install jpegoptim optipng
 

For RHEL/CentOS/AlmaLinux (YUM/DNF):

 
sudo yum install epel-release
sudo yum install jpegoptim optipng
 

How to Use the Script

Follow these simple steps to start optimizing your project's images safely:

  1. Create the script file: On your server, create a new file named optimize.sh.

  2. Copy the code: Paste the East4Serv script (provided below) into the file and save it.

  3. Make it executable: Grant execution permissions by running:

    chmod +x optimize.sh

  4. Run the script: Execute the file using:

    ./optimize.sh

  5. Follow the prompts: The script will ask for two absolute paths:

    • Target Directory: The main path containing the images you want to compress.

    • Backup Directory: The safe location where original copies will be stored.

#!/bin/bash

# =====================================================================
# Script Name: East4Serv Image Optimizer
# Description: Recursively optimizes JPG and PNG images in a directory.
#              Creates a structural backup before modifying original files.
# Copyright (c) 2026 East4Serv. All rights reserved.
# =====================================================================

# Color codes for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}=======================================${NC}"
echo -e "${GREEN}       East4Serv Image Optimizer       ${NC}"
echo -e "${GREEN}=======================================${NC}"
echo ""

# Request paths from the user
read -p "Enter the main project directory path (Target): " SOURCE_DIR
read -p "Enter the backup directory path: " BACKUP_DIR

# Validate source directory
if [ ! -d "$SOURCE_DIR" ]; then
    echo -e "${RED}Error: The target directory does not exist.${NC}"
    exit 1
fi

# Ensure absolute paths for safe string manipulation
SOURCE_DIR=$(realpath "$SOURCE_DIR")

# Create backup directory
mkdir -p "$BACKUP_DIR"
BACKUP_DIR=$(realpath "$BACKUP_DIR")

echo -e "${YELLOW}Starting backup process...${NC}"

# Find and backup images maintaining directory structure
find "$SOURCE_DIR" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) | while read -r img; do
    rel_path="${img#$SOURCE_DIR/}"
    dest_dir="$BACKUP_DIR/$(dirname "$rel_path")"
    
    mkdir -p "$dest_dir"
    cp "$img" "$BACKUP_DIR/$rel_path"
done

echo -e "${GREEN}Backup completed successfully at: $BACKUP_DIR${NC}"
echo -e "${YELLOW}Starting image optimization...${NC}"

# Check for required tools
if ! command -v jpegoptim &> /dev/null; then
    echo -e "${RED}Warning: 'jpegoptim' is not installed. JPG optimization will be skipped.${NC}"
    echo "To install: apt-get install jpegoptim (Debian/Ubuntu) or yum install jpegoptim (RHEL/CentOS)"
fi

if ! command -v optipng &> /dev/null; then
    echo -e "${RED}Warning: 'optipng' is not installed. PNG optimization will be skipped.${NC}"
    echo "To install: apt-get install optipng (Debian/Ubuntu) or yum install optipng (RHEL/CentOS)"
fi

# Optimize JPGs (quality set to 85, strips metadata)
echo "Optimizing JPG images..."
find "$SOURCE_DIR" -type f \( -iname "*.jpg" -o -iname "*.jpeg" \) -exec jpegoptim -m85 --strip-all --quiet {} \;

# Optimize PNGs (optimization level 2)
echo "Optimizing PNG images..."
find "$SOURCE_DIR" -type f -iname "*.png" -exec optipng -o2 -strip all -quiet {} \;

echo -e "${GREEN}=======================================${NC}"
echo -e "${GREEN} Optimization completed successfully!  ${NC}"
echo -e "${GREEN}=======================================${NC}"

 

Conclusion

At East4Serv, we believe in providing robust, practical solutions for the DevOps and Linux community. By integrating this script into your workflow, you can drastically reduce your server's bandwidth usage and improve your website's performance metrics.

Feel free to use, modify, and share this tool. If your business requires professional server management, advanced DevOps pipelines, or robust infrastructure solutions, the East4Serv team is ready to help you scale securely.

 

🚀

Optimized KVM Solutions

Unlock fast and reliable KVM VPS tailored for the Saudi market with massive NVMe storage and proactive management.

Get Started
🔔

Message from Support

Welcome! 👋 Do you need any help?
Support Team We are here to help

Welcome! 👋

Please fill out the form to begin.

Connecting...