You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bash实现Zip文件校验和的动态检查及自动解压

Handling Multiple Zip Files with Dynamic Checksum Validation & Extraction

Got it, let's turn your single-file script into a dynamic solution that automatically handles all zip files in your directory—no more manual filename replacements. Here's a polished, robust approach:

Full Script Implementation

#!/bin/bash

# Basic log function (replace with your existing one if you have it)
log() {
    local level="$1"
    local message="$2"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message"
}

# Initialize exit code tracker (will be set to 1 if any errors occur)
exit_code=0

# Loop through all zip files in the current directory
for zip_file in *.zip; do
    # Skip the loop if no zip files exist (avoids acting on the literal "*.zip" string)
    [[ -f "$zip_file" ]] || continue

    # Derive the matching checksum filename (adjust the pattern if your checksums use a different suffix)
    base_name="${zip_file%.zip}"
    checksum_file="${base_name}.sha512"

    # Check if the checksum file exists first
    if [[ ! -f "$checksum_file" ]]; then
        log "warning" "No checksum file found for $zip_file - skipping this file"
        continue
    fi

    # Calculate and compare checksums
    calculated_sum=$(sha512sum "$zip_file" | cut -d ' ' -f 1)
    expected_sum=$(cat "$checksum_file" | xargs)  # Trim whitespace to avoid mismatches from trailing newlines

    if [[ "$calculated_sum" != "$expected_sum" ]]; then
        log "error" "Checksum mismatch for $zip_file: calculated $calculated_sum vs expected $expected_sum"
        exit_code=1
    else
        log "info" "Checksum validated successfully for $zip_file"
        # Extract the zip (add -q for quiet mode, -o to overwrite existing files without prompting)
        if unzip -q "$zip_file"; then
            log "info" "Successfully extracted $zip_file"
        else
            log "error" "Failed to extract $zip_file"
            exit_code=1
        fi
    fi
done

# Exit with appropriate code based on errors encountered
exit ${exit_code:-0}

Key Improvements Breakdown

  • Dynamic File Detection: Uses the *.zip glob to automatically pick up all zip files in your working directory—no hardcoded filenames required.
  • Checksum File Matching: Automatically pairs each zip file with its corresponding .sha512 file (e.g., report.zip → report.sha512). Adjust the checksum_file line if your checksums follow a different naming pattern (like file.zip.sha512).
  • Error Resilience: Skips files with missing checksums instead of crashing, and tracks all errors to exit with a non-zero code only if something went wrong.
  • Robust Checksum Comparison: Trims whitespace from the expected checksum to avoid false mismatches caused by accidental newlines or spaces in the checksum file.

Quick Customization Tips

  • If you use 7z instead of unzip, replace the extraction line with 7z x -y "$zip_file" (-y auto-answers yes to overwrite prompts).
  • Add the -o flag to unzip (e.g., unzip -q -o "$zip_file") if you want to overwrite existing files without user input.
  • Swap sha512sum for another checksum tool (like md5sum) if that's what your checksum files use.

内容的提问来源于stack exchange,提问作者whatthefish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:02:59