BASH
Download Files from URL with Progress and Checksum Verification
Securely download files from a URL using `curl` or `wget`, display progress, and verify integrity with a checksum for reliable asset retrieval.
#!/bin/bash
# Configuration
DOWNLOAD_URL="https://example.com/assets/latest-version.zip"
EXPECTED_SHA256="a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2"
OUTPUT_DIR="./downloads"
OUTPUT_FILENAME="latest-version.zip"
# Full path for the downloaded file
FULL_OUTPUT_PATH="$OUTPUT_DIR/$OUTPUT_FILENAME"
# Ensure output directory exists
if [ ! -d "$OUTPUT_DIR" ]; then
echo "Creating download directory: $OUTPUT_DIR"
mkdir -p "$OUTPUT_DIR" || {
echo "Error: Failed to create directory '$OUTPUT_DIR'." >&2
exit 1
}
fi
echo "Downloading '$DOWNLOAD_URL' to '$FULL_OUTPUT_PATH'..."
# Download the file using curl with progress bar
# -L: follow redirects
# -o: write output to specified file
# -s: silent (don't show progress by default, we use --progress-bar instead)
# --progress-bar: show a simple progress bar
curl -L -o "$FULL_OUTPUT_PATH" -s --progress-bar "$DOWNLOAD_URL" || {
echo "Error: Download failed." >&2
exit 1
}
echo "Download complete."
# Verify checksum if provided
if [ -n "$EXPECTED_SHA256" ]; then
echo "Verifying file integrity with SHA256 checksum..."
if command -v sha256sum &> /dev/null; then
ACTUAL_SHA256=$(sha256sum "$FULL_OUTPUT_PATH" | awk '{print $1}')
if [ "$ACTUAL_SHA256" = "$EXPECTED_SHA256" ]; then
echo "Checksum matches! File integrity verified."
else
echo "Error: Checksum mismatch! Expected '$EXPECTED_SHA256', but got '$ACTUAL_SHA256'." >&2
rm -f "$FULL_OUTPUT_PATH" # Remove potentially corrupted file
exit 1
fi
else
echo "Warning: 'sha256sum' command not found. Cannot verify checksum." >&2
fi
else
echo "No expected SHA256 checksum provided. Skipping integrity verification."
fi
echo "File downloaded and verified successfully."
How it works: This Bash script automates downloading a file from a URL and optionally verifies its integrity using a SHA256 checksum. It first ensures a target download directory exists. It then uses `curl` with options to follow redirects, write to a specified output file, and display a progress bar. After the download, if an `EXPECTED_SHA256` value is configured, the script calculates the actual SHA256 hash of the downloaded file using `sha256sum` and compares it. This ensures that the downloaded file is not corrupted or tampered with, which is critical for fetching reliable assets, libraries, or deployment artifacts.