Compress directories from the command line, excluding node_modules and development files

This simple article provides a CLI command to compress a directory whilst excluding specific sub-directories and files.

We do a lot of custom development using modern development tools. From time-to-time we need to compress certain directories for deployment to production. In such cases, it is very common that some files and sub-directories need to be excluded, typically node_modules directories and .git</code, <code>.lock and .idea files.

Here’s a typical command that I use:

zip -r [source_dir].zip [zipped_dir] -x "*/.*" "*/.idea/*" "*.lock" "*/node_modules/*" "*/resources/assets/*"

This command zips the source excluding the specified file types and sub-directories. I’ll break it down:

zip – the command to compress to the zip format

-r – recursively compress sub-directories

[source_dir] – the directory to compress

[zipped_dir] – the compress (zipped, archived) file, containing the directory

-x – the exclude flag, items listed after this will be excluded

"*/.*" – exclude all hidden files

"*/.idea/*" – exclude all files in the hidden directories called .idea (this are IDE files)

"*.lock" – exclude all files with the lock extension

"*/node_modules/*" – exclude all node_modules directories

"*/resources/assets/*" – exclude all assets directories that reside directly inside resources directories

I hope this serves are a useful starting point for anyone out there that is looking for a clean way to compress the contents of a directory, whilst excluding some of its contents.

Aside

If you are using git you can make use of its .gitignore file to export the directory whilst excluding anything that’s being ignored in the .gitignore file(s), such as:

git archive -o latest.zip HEAD – exports the contents of the latest branch to a zipped file

Reply