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/directoryUnderstanding the Command Flags
Each flag in the command serves a specific function to ensure the process runs correctly:
--exclude='*.log': Instructs tar to ignore any file ending with the .log extension.-c: Creates a new archive.-z: Compresses the archive using gzip.-v: Verbose mode, which lists files as they are processed.-f: Specifies the filename of the resulting archive.
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/htmlYou 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/dataVerifying 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.gzReview 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.