Search This Blog

Friday, 13 May 2011

Compress all files in a directory



This is a really great terminal command that compresses every file within a directory. Here are 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.

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.

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.