Linux Tar Zip Exclude Directory

December 21st 2020

Sometimes it’s nice if you are tar zipping a directory (let’s say for a backup) and want to exclude a directory. For instance, if you are backing up a project and want to exclude the images directory (for size) or exclude the build or dist directory you can run the linux tar command with the --exclude option. However there are some quirks with using --exclude:

  1. The --exclude flag must come before the source directory
  2. Some linux distributions allow for --exclude /path/to/excluded/ and some require = such as --exclude="/path/to/excluded". From my experience all of the distributions allow the = version.
  3. The other flags such as: -czf must come directly after the tar command such as: tar -czf
  4. The excluded directory does not have the trailing backslash such as: --exclude="./wp-content/uploads"

Here is a full example excluding the uploads folder in a WordPress installation:

tar -czf backup.tgz --exclude="/var/www/wordpress/wp-content/uploads" /var/www/wordpress/wp-content/