command-line directory zip – Command to Zip Multiple Directories into Individual Zip Files

command linedirectoryzip

I have a single directory that contains dozens of directories inside of it.

I'm new to command line and I'm struggling to come up with a command that will zip each sub-directory into a unique sub-directory.zip file.

So in the end my primary directory will be filled with all of my original sub-directories, plus the corresponding .zip files that contain the zipped up content of each sub-directory.

Is something like this possible? If so, please show me how it's done.

Best Answer

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.

Parallel execution

To run them in parallel you can use &:

for i in */; do zip -0 -r "${i%/}.zip" "$i" & done; wait

We use wait to tell the shell to wait for all background tasks to finish before exiting.

Beware that if you have too many folders in your current directory, then you may overwhelm your computer as this code does not limit the number of parallel tasks.

Related Question