How To: Compress Each Folder/Directory to Separate Archives in Linux

Lets say you’ve got a bunch of folders taking up a large swathe of space which you never really use but want to keep, just not taking up stacks of your NAS… How can you easily compress them all up to individual archives of each folder? Dead easy:

Save that to a file, chmod +x it and run in the location you want to compress the folders. Every folder (and all contents within) will be compressed to its own foldername.7z archive.

With 7z, -mx9 is the flag for maximum compression, and -mmt says to use multiple CPUs to speed up compression, so omit that part if you’re on a single core machine.

2016 Now-That-I-Think-Of-It Update

The way I use this script is by simply putting it into a file called zipeach, making it executable, and then moving it to /usr/local/bin – which makes it convenient to be able to compress all folders in your pwd at whim.

Also, in case it’s important to you, the 7z format does not maintain file permissions, so if you need to preserve file permissions then you’ll likely want to compress each folder into a .tar archive, and then compress that into a .tar.7z.

How To: Compress a Directory of Files into Individual Archives

I’ve got a stack of files all thrown together in the same directory, and I wanted them compressed – simple enough, eh? Only thing is I wanted each file compressed to its own archive, so I can see at a glance what’s there, and if for some reason an archive gets corrupted, it’s just one file lost and I can replace it instead of having to dick around repairing corrupted “blob” archives that contain the entire bunch of files. And I want to be able to specify all files with a given file extension to compress.

Although I wouldn’t be surprised if you could do this in 4 lines of Perl, I don’t know flippin’ Perl (yet), so I wrote a bash script to do the job.

Bash, as it turns out, is a fiddly, finicky beast in that you really have to think about what the command-line will see under different circumstances and enclose variables in inverted commas or not in very precise ways (see this article to understand what I mean). All that if / fi stuff too… very odd.

To use the script, copy and paste it into a text file (in my case I’ve called it, save it, make the file executable using chmod +x and move it to /usr/bin or something so it’s in your path using sudo mv ./ /usr/bin/ – then run it inside any directory you want to zip files to individual archives by calling it with nds (for example) to compress all the .nds (Nintendo DS roms) in a folder into individual archives. Or use this link ;)

Anyway, job done – suggestions? improvements? props? death-threats? Let me know below!

Oh, and cheers to James McDonald for his WP-Syntax hack to stop all the embedded code appearing on a single (incredibly long) line!