BASH

Compress Web Assets for Deployment

Optimize web performance by compressing CSS, JavaScript, and image files using `tar` and `gzip` in a Bash script, reducing file sizes for faster loading.

#!/bin/bash

# Define directories containing web assets
ASSET_DIRS=(
  "./css"
  "./js"
  "./images"
  "./fonts"
)

# Output archive name with a timestamp
OUTPUT_ARCHIVE="web_assets_$(date +%Y%m%d%H%M%S).tar.gz"

# Check if any asset directories exist
ALL_DIRS_EXIST=true
for dir in "${ASSET_DIRS[@]}"; do
  if [ ! -d "$dir" ]; then
    echo "Warning: Directory '$dir' not found. Skipping."
    # Remove the non-existent directory from the list to be tarred
    ASSET_DIRS=("${ASSET_DIRS[@]/$dir}")
    ALL_DIRS_EXIST=false
  fi
done

if [ ${#ASSET_DIRS[@]} -eq 0 ]; then
  echo "No valid asset directories found to compress. Exiting."
  exit 1
fi

echo "Compressing web assets from: ${ASSET_DIRS[@]}"

# Create a gzipped tar archive of selected directories
# -c: create a new archive
# -z: compress the archive with gzip
# -v: verbosely list files processed
# -f: use archive file or device ARCHIVE
tar -czvf "$OUTPUT_ARCHIVE" "${ASSET_DIRS[@]}"

if [ $? -eq 0 ]; then
  echo "Successfully compressed assets to $OUTPUT_ARCHIVE"
  echo "Size: $(du -h "$OUTPUT_ARCHIVE" | awk '{print $1}')"
else
  echo "Error: Failed to compress assets."
  exit 1
fi
How it works: This script efficiently compresses a web project's static assets (like CSS, JavaScript, images, and fonts) into a single gzipped tar archive. It defines a list of asset directories, checks if they exist, and then uses the `tar` command with the `-czvf` flags to create a compressed, verbose archive. The archive name includes a timestamp for easy versioning. This process is highly useful for optimizing deployment sizes, creating backup snapshots of static content, or preparing assets for distribution, leading to faster loading times for web applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs