1. Command Introduction and Principles
1.1 Introduction
ZIP is a powerful cross-platform compression tool used to create ZIP format compressed files. Unlike GZIP, ZIP can directly compress entire directories and multiple files, while fully preserving file permissions, timestamps, and other metadata in the compressed file. This makes ZIP very practical for file compression and archiving applications.
1.2 Working Principle
-
DEFLATE Algorithm: Uses the same compression algorithm as gzip
-
File Collection: Organizes multiple files and directories into a single compressed package
-
Central Directory: Stores file index at the end of the file, supporting random access
-
File Header: Each file has independent header information to store metadata
-
Cross-Platform Compatibility: Uses standard ZIP file format
2. Basic Syntax
# Compress zip [options] compressed_file_name file_or_directory...# Decompress unzip [options] compressed_file_name
Common Options
# Basic compression options-r # Recursively compress directories-q # Quiet mode (no output displayed)-v # Verbose mode-0 to -9 # Compression level (0-storage, 1-fastest, 9-best, 6-default)-F # Fix corrupted zip files
# File management options-m # Delete original files after compression-u # Update compressed package (add new files)-d # Delete files from compressed package-i "file" # Include only specified files-x "file" # Exclude specified files
# Advanced options-e # Encrypt compression (set password)-P password # Use password (not secure, password visible)-X # Do not save extra file attributes-y # Preserve symbolic links-j # Discard directory structure (only save file names)-@ # Read file names from standard input
# Decompression options-l # List contents of compressed package-o # Overwrite files without prompting-d directory # Specify decompression directory-t # Test integrity of compressed package
3. Classic Usage Scenarios
3.1 Basic File Compression
# Compress a single filezip document.zip document.txt# Compress multiple fileszip archive.zip file1.txt file2.txt file3.txt# Compress a directory (recursively)zip -r project.zip project/# Use wildcardzip images.zip *.jpg *.png
3.2 File Decompression
# Decompress to current directoryunzip archive.zip# Decompress to specified directoryunzip archive.zip -d /target/directory/# List contents of compressed packageunzip -l archive.zip# Test integrity of compressed packageunzip -t archive.zip
3.3 Compression Level Control
# Fastest compression (low compression ratio)zip -1 fast.zip large_file.txt# Best compression (slow speed)zip -9 best.zip important_document.txt# Default compression (balanced)zip -6 normal.zip project/
4. Combining with Other Tool Commands
4.1 Batch Processing with find
# Find and compress specific filesfind . -name "*.log" -exec zip logs.zip {} \;# Exclude certain file typesfind . -type f ! -name "*.tmp" | zip archive.zip -@# Compress files by timefind /var/log -name "*.log" -mtime -7 | zip recent_logs.zip -@
4.2 Automating Use in Scripts
#!/bin/bash# Backup scriptautomated_backup() { local backup_dir="/backup" local source_dirs=("/home/user/documents" "/home/user/projects") local timestamp=$(date +%Y%m%d_%H%M%S) local backup_file="$backup_dir/backup_$timestamp.zip"
# Check if source directories exist for dir in "{source_dirs[@]}"; do if [ ! -d "$dir" ]; then echo "Error: Source directory does not exist: $dir" return 1 fi done
# Create backup directory mkdir -p "$backup_dir"
echo "=== Starting Backup ===" echo "Time: $(date)" echo "Backup file: $backup_file"
# Execute backup if zip -r "$backup_file" "{source_dirs[@]}" \ -x "*/node_modules/*" "*/__pycache__/*" "*.tmp" "*.log"; then echo "Backup created successfully!" echo "File size: $(du -h "$backup_file" | cut -f1)"
# Verify backup if unzip -t "$backup_file" > /dev/null 2>&1; then echo "✓ Backup verification passed"
# Clean up old backups local old_backups=$(find "$backup_dir" -name "backup_*.zip" -mtime +30 | wc -l) if [ $old_backups -gt 0 ]; then echo "Cleaning $old_backups old backups from 30 days ago..." find "$backup_dir" -name "backup_*.zip" -mtime +30 -delete fi
echo "=== Backup Completed ===" return 0 else echo "✗ Backup verification failed" # Delete invalid backup file rm -f "$backup_file" return 1 fi else echo "✗ Backup creation failed" return 1 fi}
# Main programmain() { echo "Automated backup script starting..." automated_backup exit $?}
# Script entrymain
4.3 Remote Operations with ssh
# Remote backupzip -r - . | ssh user@remote "cat > backup.zip"# Restore from remote ssh user@remote "zip -r - /remote/data" | unzip -d /local/restore/# Directly operate remote zip filessh user@remote "unzip -l /path/to/archive.zip"
5. Advanced Application Scenarios
5.1 Encrypted Compression
#!/bin/bash# Secure backup systemsecure_backup() { local source="$1" local backup_dir="/secure_backup" local timestamp=$(date +%Y%m%d_%H%M%S)
# Interactive password input read -s -p "Enter encryption password: " password echo # Create encrypted compressed package zip -e -P "$password" -r "$backup_dir/secure_$timestamp.zip" "$source" echo "Encrypted backup completed: secure_$timestamp.zip"}
# Batch encrypt filesencrypt_files() { local files=("$@") local password=$(openssl rand -base64 16) echo "Using password: $password" zip -e -P "$password" encrypted_files.zip "{files[@]}" # Securely save password echo "$password" > backup_password.txt chmod 600 backup_password.txt echo "Password saved to backup_password.txt"}
# Main programmain() { echo "Automated backup script starting..."
# Call secure backup function (needs parameter) echo "Executing secure backup..." secure_backup "$1"
# Call encrypt files function (needs parameter) echo "Executing file encryption..." shift # Remove first parameter encrypt_files "$@"
exit $?}
# Script entrymain "$@"
# Usage# Backup directory and encrypt files./script.sh /path/to/backup file1.txt file2.jpg
# Only backup directory./script.sh /path/to/backup
# Only encrypt files./script.sh "" file1.txt file2.jpg
5.2 Incremental Backup System
#!/bin/bash# Zip-based incremental backupincremental_backup() { local source_dir="$1" local backup_dir="$2" local timestamp=$(date +%Y%m%d_%H%M%S) local snapshot_file="$backup_dir/last_snapshot.txt"
# Check parameters if [ -z "$source_dir" ] || [ -z "$backup_dir" ]; then echo "Error: Source directory and backup directory must be specified" return 1 fi
# Create backup directory mkdir -p "$backup_dir"
# Create file list find "$source_dir" -type f > "/tmp/current_files.txt"
if [ -f "$snapshot_file" ]; then # Incremental backup: only back up new or modified files echo "Executing incremental backup..." zip -r "$backup_dir/incremental_$timestamp.zip" -@ < <( comm -13 <(sort "$snapshot_file") <(sort "/tmp/current_files.txt") ) else # First full backup echo "Executing full backup..." zip -r "$backup_dir/full_$timestamp.zip" "$source_dir" fi
# Check if zip command was successful if [ $? -eq 0 ]; then # Update snapshot file cp "/tmp/current_files.txt" "$snapshot_file" echo "Backup completed: $backup_dir/incremental_$timestamp.zip" else echo "Backup failed!" fi
# Clean up temporary files rm -f "/tmp/current_files.txt"}
# Main programmain() { echo "Automated backup script starting..."
# Check parameter count if [ $# -lt 2 ]; then echo "Usage: $0 <source_directory> <backup_directory>" echo "Example: $0 /home/user/documents /backup" exit 1 fi
incremental_backup "$1" "$2" exit $?}
# Script entrymain "$@"
# Usage# First run (full backup) ./backup_script.sh /path/to/source /path/to/backup
# Subsequent runs (incremental backup) ./backup_script.sh /path/to/source /path/to/backup
5.3 Split Compression of Large Files
#!/bin/bash# Split compression of large filessplit_compression() { local source="$1" local split_size="100m" # Each split is 100MB local base_name="large_archive"
# Check if source directory exists if [ -z "$source" ] || [ ! -e "$source" ]; then echo "Error: A valid source path must be specified" return 1 fi
# Create split zip (requires zip 3.0+) echo "Starting split compression: $source" zip -r -s "$split_size" "$base_name.zip" "$source" echo "Split compression completed: ${base_name}.z01, ${base_name}.z02, ..."}
# Merge and extract split filesmerge_and_extract() { local base_name="$1" local target_dir="$2"
# Check parameters if [ -z "$base_name" ] || [ -z "$target_dir" ]; then echo "Error: Base name and target directory must be specified" return 1 fi
# Create target directory mkdir -p "$target_dir"
echo "Starting merge and extract split files..."
# Merge split files (if needed) if [ ! -f "${base_name}.zip" ]; then echo "Merging split files..." zip -F "${base_name}.zip" --out "${base_name}_fixed.zip" unzip "${base_name}_fixed.zip" -d "$target_dir" else unzip "${base_name}.zip" -d "$target_dir" fi echo "Extraction completed to: $target_dir"}
# Traditional method: split then compress (compatible with older versions)traditional_split() { local source="$1" local split_size="100M"
# Check if source directory exists if [ -z "$source" ] || [ ! -e "$source" ]; then echo "Error: A valid source path must be specified" return 1 fi
echo "Using traditional method for split compression: $source" # First package then split tar -cf - "$source" | split -b "$split_size" - "archive_part_" echo "Splitting completed, starting to compress each part..."
# If needed, compress the split files for part in archive_part_*; do echo "Compressing: $part" zip "${part}.zip" "$part" rm "$part" done echo "Traditional split compression completed"}
# Display usage instructionsusage() { echo "Usage:" echo " $0 split <source_directory> # Split compression" echo " $0 merge <base_name> <target_directory> # Merge and extract" echo " $0 traditional <source_directory> # Traditional split method" echo "" echo "Example:" echo " $0 split /path/to/large_folder" echo " $0 merge large_archive /path/to/extract" echo " $0 traditional /path/to/large_folder"}
# Main programmain() { case "$1" in split|s) if [ -z "$2" ]; then echo "Error: Please specify the source directory to compress" usage exit 1 fi echo "Starting split compression..." split_compression "$2" ;; merge|m) if [ -z "$2" ] || [ -z "$3" ]; then echo "Error: Please specify base name and target directory" usage exit 1 fi echo "Starting merge and extract..." merge_and_extract "$2" "$3" ;; traditional|t) if [ -z "$2" ]; then echo "Error: Please specify the source directory to compress" usage exit 1 fi echo "Starting traditional split compression..." traditional_split "$2" ;; *) usage exit 1 ;; esac}
# Script entryif [ $# -eq 0 ]; then usage exit 1fi
main "$@"
# Usage# Function 1: Split a large directory into 100MB zip splits./script.sh split /path/to/large_directory# Generated files:# large_archive.zip, large_archive.z01, large_archive.z02, ...
5.4 Comparison with Other Compression Tools
# zip vs tar.gz
zip -r project.zip project/ # Cross-platform, random access
tar -czf project.tar.gz project/ # Linux standard, better compression ratio
# zip vs 7z
zip -r archive.zip files/ # Widely supported, standard format
7z a archive.7z files/ # Higher compression ratio, more features
# zip vs rar
zip -r archive.zip files/ # Open source, free
rar a archive.rar files/ # Commercial software, specific features
6. Conclusion
By gaining a deep understanding and mastery of the ZIP format, we can build powerful cross-platform file management solutions. Although the tar command may be more favored and commonly used by developers in pure Linux environments, the ZIP format, with its excellent cross-platform adaptability and ease of use, plays an indispensable role in many practical application scenarios.
#zip command #Linux decompression command #Linux operation and maintenance command #Linux command from beginner to expert【If there are any omissions, please correct them!】