Commands.page Logo

Compress Ubuntu Directory and Exclude .log Files

Managing disk space and creating efficient backups on Ubuntu often requires compressing directories while omitting unnecessary data. This guide explains how to use the tar command to archive a folder while automatically excluding all .log files. You will learn the specific syntax and flags needed to streamline your compression tasks without including bulky log data.

The Tar Command with Exclude Flag

The most effective way to compress a directory while filtering out specific file types in Ubuntu is using the tar utility with the --exclude option. This allows you to create a compressed archive without permanently deleting the original log files.

Open your terminal and use the following syntax:

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

Understanding the Command Flags

Each flag in the command serves a specific function to ensure the process runs correctly:

Practical Example

If you want to back up the /var/www/html directory but want to leave out all log files to save space, you would run:

tar --exclude='*.log' -czvf website_backup.tar.gz /var/www/html

You can also chain multiple exclude flags if you need to omit other file types simultaneously, such as temporary files:

tar --exclude='*.log' --exclude='*.tmp' -czvf backup.tar.gz /home/user/data

Verifying the Archive

After the compression completes, you can verify the contents of the archive to ensure no .log files were included. Use the list command to inspect the archive contents:

tar -tzvf archive_name.tar.gz

Review the output list. If the command was successful, you will see your directory structure and files, but no entries ending in .log will appear in the list.