Commands.page Logo

How to Download and Verify Checksums in Ubuntu Automatically

This guide explains how to secure your Ubuntu system by automating file downloads and integrity checks. You will learn to use command-line tools to fetch files and validate their SHA256 checksums in a single step. By following these methods, you ensure data integrity and protect against corrupted or tampered files without manual intervention.

Prerequisites

Ubuntu comes with the necessary tools pre-installed. You need wget or curl for downloading and sha256sum for verification. To confirm they are available, open your terminal and run which wget and which sha256sum. If any command is missing, install them using sudo apt update && sudo apt install wget coreutils.

The One-Liner Method

For quick tasks, you can chain commands together using the && operator. This downloads the file and only runs the verification if the download succeeds. Replace the URL and expected hash with your specific values.

wget https://example.com/file.iso && echo "expected_hash  file.iso" | sha256sum -c

If the output returns file.iso: OK, the file is intact. If it returns FAILED, the file is corrupted or tampered with and should be deleted immediately.

The Automated Bash Script

For repeated tasks, create a reusable script. This script accepts a URL and an expected checksum as arguments, downloads the file, and verifies it automatically.

  1. Create a new file named verify-download.sh.
  2. Paste the following code into the file:
#!/bin/bash

if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <url> <filename> <expected_checksum>"
    exit 1
fi

URL=$1
FILENAME=$2
EXPECTED_HASH=$3

echo "Downloading $FILENAME..."
wget -q "$URL" -O "$FILENAME"

if [ $? -ne 0 ]; then
    echo "Download failed."
    exit 1
fi

echo "Verifying checksum..."
echo "$EXPECTED_HASH  $FILENAME" | sha256sum -c

if [ $? -eq 0 ]; then
    echo "Verification successful. File is safe."
else
    echo "Verification failed. Deleting corrupted file."
    rm "$FILENAME"
    exit 1
fi
  1. Make the script executable by running chmod +x verify-download.sh.
  2. Run the script with your file details:
./verify-download.sh https://example.com/file.iso file.iso a1b2c3d4e5f6...

This approach ensures every download is validated instantly, streamlining your workflow while maintaining system security.