BASH

Downloading Files and Extracting Archives with Bash

Learn to use bash scripts for programmatically downloading files from URLs and automatically extracting common archive formats like .tar.gz or .zip.

#!/bin/bash

# Configuration
DOWNLOAD_URL="https://example.com/archive.tar.gz" # URL of the file to download
# DOWNLOAD_URL="https://github.com/someuser/somerepo/archive/refs/heads/main.zip"
OUTPUT_DIR="./downloads" # Directory to save the downloaded file and extracted contents

# Create the output directory if it doesn't exist
mkdir -p "$OUTPUT_DIR" || { echo "Error: Could not create output directory!"; exit 1; }

# Extract filename from URL
FILENAME=$(basename "$DOWNLOAD_URL")
DOWNLOAD_PATH="$OUTPUT_DIR/$FILENAME"

echo "Downloading '$FILENAME' from '$DOWNLOAD_URL' to '$DOWNLOAD_PATH'..."

# Download the file using curl
# -L: Follow redirects
# -O: Write output to a local file named like the remote file (cannot be used with -o)
# -f: Fail silently (no output at all) on HTTP errors
# Using -o to specify output path explicitly
curl -Lfo "$DOWNLOAD_PATH" "$DOWNLOAD_URL" || { echo "Download failed!"; exit 1; }

echo "Download complete. Checking file type for extraction..."

# Determine file type and extract
case "$FILENAME" in
    *.tar.gz|*.tgz)
        echo "Extracting .tar.gz archive..."
        tar -xzf "$DOWNLOAD_PATH" -C "$OUTPUT_DIR" || { echo "Extraction failed!"; exit 1; }
        ;;
    *.tar.bz2|*.tbz)
        echo "Extracting .tar.bz2 archive..."
        tar -xjf "$DOWNLOAD_PATH" -C "$OUTPUT_DIR" || { echo "Extraction failed!"; exit 1; }
        ;;
    *.zip)
        echo "Extracting .zip archive..."
        unzip "$DOWNLOAD_PATH" -d "$OUTPUT_DIR" || { echo "Extraction failed!"; exit 1; }
        ;;
    *)
        echo "Unknown archive type or no extraction needed for '$FILENAME'."
        ;;
esac

# Optional: Clean up the downloaded archive file
# rm "$DOWNLOAD_PATH"
# echo "Removed downloaded archive: $DOWNLOAD_PATH"

echo "Script finished."
How it works: This script automates downloading a file from a URL using `curl` and then intelligently extracts its contents based on the file extension. It supports common archive formats like `.tar.gz`, `.tar.bz2`, and `.zip`. The script ensures an output directory exists, handles download/extraction errors, and provides an optional step to clean up the downloaded archive file after extraction.

Need help integrating this into your project?

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

Hire DigitalCodeLabs