Compress All Files in a Directory by Command Line

Oct 4, 2010 - 1 Comment


This is a really great terminal command that compresses every file within a directory, turning them into a zip archive. We’ll offer two variants of it; one that removes the original source file and leaves only the compressed files, and another command that leaves the uncompressed source files intact. This has been tested and works in Mac OS X and Linux.

Compress All Files in a Directory, & Remove Source Files

This version compresses all items in the current directory and then removes the original source uncompressed file:

for item in *; do zip -m "${item}.zip" "${item}"; done

Remember the * signifies all files in the current directory, so be sure you are in the directory you want to compress before executing the command. You can always double-check what directory you are working in with the ‘pwd’ command too.

I tested this out and after reading it on StevenF and on average it compressed files 66%, which is a significant reduction. If you have a largely infrequently accessed downloads or other archives folder, this command can really conserve disk space. Obviously since it compresses the files, it wouldn’t make sense to use it in a directory where things are regularly accessed.

Compress All Files in a Directory, Maintain Original Files

You can also use the above command to compress all of the files within a directory, but still maintain the original files or folders as uncompressed. The command is practically identical, just leave out the -m flag:

for item in *; do zip "${item}.zip" "${item}"; done

You will now have compressed all files in the present working directory (pwd) and the original source files will remain in place uncompressed as well.

These command work in Mac OS X and Linux, and likely other Unix variants as well.

Check out more command line tips if you are interested.


Related articles:

Posted by: Manish Patel in Command Line, Tips & Tricks

One Comment

» Comments RSS Feed

  1. Jared Hecker says:

    ‘find’ is faster:

    find . -exec gzip {} \;

Leave a Reply


Shop on and help support OSXDaily!

Subscribe to OSXDaily

Subscribe to RSS Subscribe to Twitter Feed Follow on Facebook Subscribe to eMail Updates

Tips & Tricks


iPhone / iPad



Shop on Amazon to help support this site