Commands.page Logo

How to Compress Ubuntu Directory Excluding Temp Files

Managing disk space and backup efficiency often requires ignoring unnecessary data. This article demonstrates how to generate a compressed archive of a directory in Ubuntu while automatically excluding temporary files. We will utilize the tar utility with exclusion flags to ensure only relevant data is stored.

Use the Tar Command with Exclude Flags

The tar utility is the standard tool for creating archives in Linux. To create a compressed gzip archive while skipping specific files, you need the --exclude option. The basic syntax combines the compression flags with the exclusion pattern.

tar --exclude='pattern' -czvf archive_name.tar.gz /path/to/directory

Exclude Specific Temporary Folders

Many applications store temporary data in folders named tmp or cache. You can exclude these directories by specifying their names relative to the source path. For example, to backup a project folder but ignore its local tmp directory, run:

tar --exclude='tmp' -czvf project_backup.tar.gz ./project_folder

You can chain multiple exclude flags to ignore several directories at once. This is useful if you need to skip both tmp and logs folders during the compression process.

tar --exclude='tmp' --exclude='logs' -czvf backup.tar.gz ./data

Exclude Files by Extension

Temporary files often share specific extensions such as .tmp, .swp, or .cache. You can exclude these files using wildcard patterns. This ensures that any file matching the extension is left out of the final archive regardless of its location within the directory tree.

tar --exclude='*.tmp' --exclude='*.cache' -czvf clean_backup.tar.gz ./home/user

Verify the Archive Contents

After creating the archive, it is good practice to verify that the temporary files were successfully excluded. You can list the contents of the tar file without extracting it using the -t flag.

tar -tvf clean_backup.tar.gz

Review the output to confirm that no files matching your exclusion patterns appear in the list. This ensures your backup remains lightweight and contains only the necessary data.