How to zip a directory by excluding specified sub-directories

On Unix, the common zip command used to compress a folder is:

zip -r <zip_file_name>.zip <directory_name>

However, sometimes we might require an option to zip the directory by excluding few sub-directories, especially the ones with huge size and are not required. One easy workaround is to zip normally, extract and then delete the undesired sub-directories. But if the zipped file has to be transferred to other machine, size matters. This was in fact the context where I required it.

So jumping to the required command for this task:

zip -r <zip_file_name>.zip <directory_name> -x <directory_name>/<undesired_sub_directory1_name>\* <directory_name>/<undesired_sub_directory2_name>\* <directory_name>/<undesired_file_name>


Lets say there’s a ‘test’ directory with 1,2,3,4,5 sub-directories (with some files in them) and files abc.txt and xyz.txt

$ zip -r test

The above command compresses the entire test directory and upon extraction all the sub-folders and files can be observed.

With exclusion:

$ zip -r test -x test/1\* test/3\* test/abc.txt

adding: test/ (stored 0%)
adding: test/2/ (stored 0%)
adding: test/2/2.txt (stored 0%)
adding: test/4/ (stored 0%)
adding: test/4/4.txt (stored 0%)
adding: test/5/ (stored 0%)
adding: test/5/5.txt (stored 0%)
adding: test/xyz.txt (stored 0%)

This command forms by excluding 1,3 sub-directories and the file abc.txt. Upon extraction, only 2,4,5 sub-directories and xyz.txt are available.

$ unzip
creating: test/
creating: test/2/
extracting: test/2/2.txt
creating: test/4/
extracting: test/4/4.txt
creating: test/5/
extracting: test/5/5.txt
extracting: test/xyz.txt

Please note that for exclusion of sub-directories, its the backward slash ‘\’ followed by * at the end of each sub-directory exclusion.

Leave a Comment