求编写Bash脚本:解压拆分归档文件后自动删除已处理分片
Solution: Extract Split Archive Parts & Delete Them As You Go
Alright, let's tackle this space-saving problem you're facing. The issue with your original cat *.gz* | tar zxvf - -i command is that it requires keeping all the split parts around while extracting, which eats up too much space on your new server. Here's a bash script that processes each split part one by one, deleting it immediately after it's successfully extracted—so you only ever need space for one part plus the extracted files at any time.
The Bash Script
#!/bin/bash # Define the path prefix for your split archive parts ARCHIVE_PARTS="/arch/to_arch.gz_*" # Process each part in the correct order (split's aa/ab/ac... follows lex order, which matches creation order) for part in $ARCHIVE_PARTS; do # Skip if the path isn't a regular file (avoids directories or invalid matches) if [ ! -f "$part" ]; then continue fi echo "Processing archive part: $part" # Pipe the part through gzip decompression to tar (matches your original command's flow) cat "$part" | gzip -d | tar xvf - -i # Check if extraction was successful before deleting if [ $? -eq 0 ]; then echo "Successfully processed $part. Deleting it now..." rm -f "$part" else echo "ERROR: Failed to process $part. Skipping deletion to avoid data loss." exit 1 fi done echo "All archive parts processed and cleaned up successfully!"
Key Details & Usage
- Save the script: Copy the code above into a file named
extract_and_clean.sh. - Make it executable: Run
chmod +x extract_and_clean.shto grant execution permissions. - Run the script: Execute it with
./extract_and_clean.sh(or use the full path if it's not in your current directory).
Important Notes
- Order matters: The script relies on the split parts being named in lex order (
aa,ab,ac, etc.), which is the default behavior of thesplitcommand you used. This ensures the tar archive is reconstructed correctly. - Error safety: The script checks if each part extracts successfully before deleting it. If any part fails, it exits immediately to prevent accidental deletion of unprocessed files.
-iparameter: This matches your original command and tells tar to ignore minor archive corruption, which is useful when dealing with split files (though it's safe to remove if you're confident your archive is intact).
内容的提问来源于stack exchange,提问作者Ekstermin Sir
相关产品推荐
相关产品推荐

