Skip to content

Instantly share code, notes, and snippets.

@junio256
Last active September 12, 2023 11:19
Show Gist options
  • Save junio256/cd44951debcd2f8a23310775d4348090 to your computer and use it in GitHub Desktop.
Save junio256/cd44951debcd2f8a23310775d4348090 to your computer and use it in GitHub Desktop.
Unzip recursivelly
#!/usr/bin/env bash
# Unzip Recursively
# -----------------
# Unzip recursively all zip files in a directory
# Usage: unzip.sh <zip_file>
#
# Set input parameters
file_path="$1"
remove="$2"
if [ $# -eq 0 ]; then
echo "Unzip Recursively"
echo "-----------------"
echo "Unzip recursively all zip files in a directory"
echo "Usage: unzip.sh <zip_file>"
echo "<zip_file> may be a single file or a directory"
exit 1
fi
cleanup_and_exit() {
echo "Received Ctrl+C. Cleaning up and exiting..."
pkill -f "unzip"
exit 1
}
# Trap the SIGINT (Ctrl+C) signal
trap cleanup_and_exit SIGINT
# Check if the input file exists
if [ ! -e "$file_path" ]; then
echo "Error: The input file does not exist."
exit 1
fi
_filename=$(basename "$file_path" .zip)
unzip_output="$_filename-unzipped"
# Create a directory for unzipping
if [ -e "$unzip_output" ]; then
echo "WARNING: $unzip_output already exists"
read -r -p "Do you want to overwrite it? [Y/n] " -i "Y" answer
case $answer in
Y|y|yes)
rm -rf "$unzip_output"
;;
*)
exit 0
;;
esac
fi
mkdir "$unzip_output"
# Copy the input file to the unzip directory
cp "$file_path" "$unzip_output/"
# Check if any zip files exist in the directory
zip_files=$(find "$unzip_output" -type f -name "*.zip")
if [ -z "$zip_files" ]; then
echo "Error: The folder does not contain any zip files."
exit 1
fi
function unzip_file {
for zip_file in $zip_files; do
# Extract the file name and directory
file_name=$(basename "$zip_file" )
dir_name=$(dirname "$zip_file")
# Check if the file name contains invalid characters
if echo "$file_name" | grep -q '[\\/]'; then
echo "WARN: File with invalid name $file_name"
# Replace invalid characters in the filename
file_name=$(echo "$file_name" | sed "s/[\/]/ - /g")
_zf="$dir_name/$file_name"
mv "$zip_file" "$_zf"
zip_file="$_zf"
echo "Renamed to $file_name"
fi
if [ $(basename $file_name | rev | cut -f 1- -d "." | rev ) -eq "zip" ]; then
exit 1
fi
# Unzip the file
echo "Unzipping $zip_file \n..."
unzip -B $zip_file -d $dir_name || exit 1
echo "Finished! unzipping $zip_file"
# Remove zip file to block infinite recursion
rm $zip_file
done
# Update the list of zip files
zip_files=$(find "$unzip_output" -type f -name "*.zip")
# Recursively process the remaining zip files
if [ -n "$zip_files" ]; then
unzip_file
else
echo "Success: All zip files have been unzipped ๐ŸŽ†๐Ÿ™"
fi
}
unzip_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment