← Back to all snippets
BASH

File Integrity Check with MD5/SHA256

Ensure file integrity in Bash scripts using MD5 or SHA256 checksums to verify downloads or detect unauthorized modifications, crucial for secure deployments.

#!/bin/bash

FILE_TO_CHECK="example.tar.gz"
EXPECTED_MD5="d41d8cd98f00b204e9800998ecf8427e" # MD5 for an empty file
EXPECTED_SHA256="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" # SHA256 for an empty file

# Create a dummy file for demonstration
touch "$FILE_TO_CHECK"
echo "Created dummy file: $FILE_TO_CHECK"

# --- MD5 Check ---
if command -v md5sum &> /dev/null; then
    echo -e "
Performing MD5 check..."
    CURRENT_MD5=$(md5sum "$FILE_TO_CHECK" | awk '{print $1}')
    
    if [ "$CURRENT_MD5" == "$EXPECTED_MD5" ]; then
        echo "MD5 Check: SUCCESS - File integrity verified."
    else
        echo "MD5 Check: FAILED - File has been altered or is corrupt."
        echo "Expected: $EXPECTED_MD5"
        echo "Actual:   $CURRENT_MD5"
    fi
else
    echo "md5sum command not found. Skipping MD5 check."
fi

# --- SHA256 Check ---
if command -v sha256sum &> /dev/null; then
    echo -e "
Performing SHA256 check..."
    CURRENT_SHA256=$(sha256sum "$FILE_TO_CHECK" | awk '{print $1}')
    
    if [ "$CURRENT_SHA256" == "$EXPECTED_SHA256" ]; then
        echo "SHA256 Check: SUCCESS - File integrity verified."
    else
        echo "SHA256 Check: FAILED - File has been altered or is corrupt."
        echo "Expected: $EXPECTED_SHA256"
        echo "Actual:   $CURRENT_SHA256"
    fi
else
    echo "sha256sum command not found. Skipping SHA256 check."
fi

# Clean up dummy file
rm "$FILE_TO_CHECK"
How it works: This script demonstrates how to verify the integrity of a file using MD5 or SHA256 checksums. It first checks for the presence of `md5sum` and `sha256sum` commands. It then calculates the current checksum of a specified file and compares it against a predefined expected value. This is crucial for ensuring that downloaded files haven't been tampered with or corrupted during transfer, providing a basic security and reliability check for various deployment or data processing scenarios.

Need help integrating this into your project?

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

Hire DigitalCodeLabs