Linux

How to Recursively Zip a Folder While Ignoring Specific Directories

Zachary Carciu 3 min read

How to Recursively Zip a Folder While Ignoring Specific Directories

When zipping a project folder, you may want to exclude large directories like node_modules to reduce file size and speed up compression. The zip command in Linux and macOS provides an easy way to do this using the -x flag.

Recursively Zip a Folder While Ignoring node_modules

To create a ZIP archive of a project folder while ignoring node_modules, use the following command:

zip -r my-project.zip project/ -x "project/node_modules/*"

Explanation:

  • zip -r my-project.zip project/ → Recursively zip the project/ directory into my-project.zip.
  • -x "project/node_modules/*" → Exclude everything inside project/node_modules/.

Exclude Multiple Directories

If you need to exclude multiple directories (e.g., .git, tmp), you can extend the -x option:

zip -r my-project.zip project/ -x "project/node_modules/*" "project/.git/*" "project/tmp/*"

Alternative: Zipping from Within the Project Directory

If you are inside the project/ directory, you can use:

cd project
zip -r ../my-project.zip . -x "node_modules/*"

This ensures node_modules is ignored while compressing everything else in project/.

Frequently Asked Questions

Can I use wildcards to exclude multiple similar directories?

Yes, you can use wildcards to exclude multiple directories with similar patterns. For example, to exclude all directories that end with “cache”:

zip -r my-project.zip project/ -x "project/*cache/*"

How do I verify which files are included in my zip archive?

You can use the -sf flags with the zip command to display the files that would be included without actually creating the archive:

zip -sf -r my-project.zip project/ -x "project/node_modules/*"

Does the order of the excluded directories matter?

No, the order of excluded directories doesn’t matter. You can list them in any order after the -x flag.

Can I create a file with exclusion patterns instead of listing them on the command line?

Yes, for complex exclusion patterns, you can use the -x@excludelist.txt syntax, where excludelist.txt contains one pattern per line:

# Create excludelist.txt with patterns
echo "project/node_modules/*" > excludelist.txt
echo "project/.git/*" >> excludelist.txt

# Use the file with zip
zip -r my-project.zip project/ -x@excludelist.txt

How do I exclude hidden files and directories?

To exclude all hidden files and directories (those starting with a dot), use:

zip -r my-project.zip project/ -x "project/.*" "project/*/.*"

Conclusion

Using the zip command with the -x flag allows you to efficiently create ZIP archives while excluding unnecessary files or directories. This is particularly useful when sharing projects or creating backups without including large dependencies like node_modules.