Linux Commands

How to exclude files from a zip archive in Linux

Collecting multiple files into a single file is called archiving, and “zip” is one of the widely used archive formats that come with lossless data compression support. Archiving files is an efficient way to save your machine’s storage and make it easier to transfer files through email or FTP.
Linux has a built-in zip utility to archive the files with a set of options. This utility provides several methods to archive the files. When you archive a directory using zip utility, it includes all the files in that directory and zip it. So, is it possible to archive a file and excluding the particular files using the “zip” utility? The answer is yes! The “zip” is a versatile Linux utility that lets you archive files, excluding specified files or folders. How does it happen? Let’s begin:

How to exclude files and directories when using “zip” in Linux:

You can archive any directory excluding a particular file using the “-x” flag with the “zip” utility. The general syntax is mentioned below:

$zip -r [file_name.zip] [files/folder to zip] -x [file path/name to exclude]

Let’s understand it through an example; I have created a directory by the name of “images” that contains 3 image files, one zipped file, and one sub-directory (my folder) as shown in the following image :

Now launch terminal and type:

$zip -r myfile.zip images -x /images/img2.png

In the above command, I am compressing the “images” directory and excluding an image file “img2.jpg” and saving it as “myfile.zip.”

As it can be seen that “myfile.zip” did not include the “img2.jpg” file. You can also exclude file by mentioning the extension of the file; for instance, I want to exclude all “.jpg” files in the “images” directory and archive it:

$zip -r myfile.zip images -x *.jpg

All the “jpg” files have been excluded in the zip file. You can exclude multiple files and directories by mentioning them in the following way:

$zip -r myfile.zip images -x /images/img2.jpg -x

/images/all_images.zip

The “img2.jpg” and “all_images.zip” files will not be archived:

Conclusion:

Keeping the files in an archive saves a lot of your machine’s storage and helps manage tons of files and folders. In Linux “zip” utility is used to archive files/directories. In this write-up, we learned how to use the “zip” utility to archive the directory, excluding a specific file or folder. The “zip” utility comes with quite useful options for executing “zip –help” in the terminal.

About the author

Sam U

I am a professional graphics designer with over 6 years of experience. Currently doing research in virtual reality, augmented reality and mixed reality.
I hardly watch movies but love to read tech related books and articles.