2014-04-05

zip all directories or folders at current path in linux by its' own name.zip respectively, then remove source after zip.


Source URL: http://unix.stackexchange.com/questions/68489/command-to-zip-multiple-directories-into-individual-zip-files


Given solution:

You can use this loop in bash:
for i in */; do zip -r "${i%/}.zip" "$i"; done
i is the name of the loop variable. */ means every subdirectory of the current directory, and will include a trailing slash in those names. Make sure you cd to the right place before executing this. "$i" simply names that directory, including trailing slash. The quotation marks ensure that whitespace in the directory name won't cause trouble. ${i%/} is like $i but with the trailing slash removed, so you can use that to construct the name of the zip file.
If you want to see how this works, include an echo before the zip and you will see the commands printed instead of executed.



What i'm using:
for i in */; do zip -rm9 "${i%/}.zip" "$i"; done
zip  -r : zip recursively
zip  -m : zip and remove source file(move target files into zip).
zip  -9 : zip with compress better


Steps I did:


  1. Navigate to target directory: cd /opt/Programs/apache-tomcat-7.0.39.2/webapps/ProjectABC/WEB-INF/classes/archive
  2. Create bash script file: vi zip_folders.sh
  3. After enable edit mode by press "i", then paste script and enhance to my requirement: for i in */; do zip -rm9 "${i%/}.zip" "$i"; done
  4. Exit edit mode by: Press Esc.
  5. Save file and exit VI editor by: :wq
  6. Make file "runable" by: chmod +x zip_folders.sh
  7. then run file by: ./zip_folders.sh