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:

  1. #!/bin/bash
  2. for folder in */
  3. do
  4.   7z a -mx9 -mmt "${folder%/}.7z" "$folder"
  5. done

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.

6 thoughts on “How To: Compress Each Folder/Directory to Separate Archives in Linux”

  1. Great example and very simple. However I have one question. Im trying to create the folder archives in a different folder e.g.

    All folders in

    are archived and sent to:


    im sure this would be quite simple but im not sure how to do this.

    Thanks :-D

      1. Thanks that seems so much simpler than what i came up with.

        for folder in $(find /backup/live/ -maxdepth 1 -mindepth 1 -name '[!.]*' -exec basename  {} ;)
        7z a -mmt /backup/archive/${folder}/${folder}-backup-$(date +%d-%m-%Y).7z /backup/live/${folder} >> /tmp/backup-7z
    1. Happy to serve =D

      Looking back on this I probably should have mentioned that 7z archives won’t preserve file permissions and stuff, so this is only for things where you only care about the files themselves and not ownership issues (if you need to preserve ownership then it needs to be tar’d then 7z’d).

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.