Advertisement
Guest User

recursiveunzip.sh

a guest
Apr 17th, 2015
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.19 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # This script is public domain. You may use this for any purpose.
  4. #
  5. # By using this script, you acknowledge that the author is not liable
  6. # for any damages or lost data.
  7.  
  8. # recursiveunzip
  9. # 0.0.1
  10. #
  11. # Unzips a zip file containing other zip files into a directory
  12. # structure, with optional deletion of the interior zip files.
  13.  
  14. IllegalArgs=1
  15. FileNotFound=2
  16. CannotCreateFolder=3
  17.  
  18. main()
  19. {
  20.     fileName=$(basename -s .zip "$1")
  21.     mkdir $fileName 2> /dev/null
  22.     folderCreationFailure=$?
  23.     if [ $folderCreationFailure != 0 ]; then
  24.         # there's already a folder with this name, or you don't have
  25.         # write permissions. For the sake of safety, we exit.
  26.         echo "Can't create the folder $fileName in $(pwd)"
  27.         exit $CannotCreateFolder
  28.     fi
  29.     unzip -d "$fileName" "$fileName".zip
  30.     cd "$fileName"
  31.  
  32.     oldIFS="$IFS"; IFS=$'\n'
  33.     zipFiles=( $(ls *.zip 2> /dev/null) ); IFS="$oldIFS"
  34.     if [ $zipFiles ]; then
  35.         for file in "$zipFiles"; do
  36.             main "$file"
  37.         done
  38.     fi
  39. }
  40.  
  41. # User interface starts here.
  42.  
  43. if [ $# != 1 ]; then
  44.     echo "Please pass in a single valid zip file."
  45.     exit $IllegalArgs
  46. fi
  47.  
  48. if [ ! -r $1 ]; then
  49.     echo "You don't have read permissions for the file $1, or it doesn't exist."
  50.     exit $FileNotFound
  51. fi
  52.  
  53. isZip=$(file "$1" | grep -e "Zip archive data" -c)
  54.     # This uses the `file` utility to make sure it is a zip file. `grep`
  55.     # counts the matches and then we put this value in the status
  56.     # variable.
  57.  
  58. if [ ! $isZip ]; then    # the file is not a zip file
  59.     echo "You must pass in a .zip file."
  60.     exit $IllegalArgs
  61. else
  62.     fileNameOriginal=$(basename -s .zip "$1")
  63.     oldpwd="$(pwd)"
  64.  
  65.     main "$1"
  66.  
  67.     cd "$oldpwd"
  68.     prompt="Would you like to remove all zip files inside $fileNameOriginal? [yes/no]  "
  69.     tree "$fileNameOriginal"
  70.  
  71.     while [ ! $answer ]; do
  72.         read -p "$prompt" answer
  73.         if [ "$answer" != "yes" ] &&  [ "$answer" != "no" ]; then
  74.             unset answer
  75.         fi
  76.     done
  77.  
  78.     if [ "$answer" == "yes" ]; then
  79.         find "$fileNameOriginal" -type 'f' -name '*.zip' -delete
  80.     fi
  81.  
  82.     tree "$fileNameOriginal"
  83.  
  84.     exit 0
  85. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement