使用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
*.zipglob 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
.sha512file (e.g.,report.zip→report.sha512). Adjust thechecksum_fileline if your checksums follow a different naming pattern (likefile.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
7zinstead ofunzip, replace the extraction line with7z x -y "$zip_file"(-yauto-answers yes to overwrite prompts). - Add the
-oflag tounzip(e.g.,unzip -q -o "$zip_file") if you want to overwrite existing files without user input. - Swap
sha512sumfor another checksum tool (likemd5sum) if that's what your checksum files use.
内容的提问来源于stack exchange,提问作者whatthefish
相关产品推荐
相关产品推荐

