How to Exclude Files When Creating Tar Archive in Ubuntu
Creating backups on Ubuntu often requires leaving out temporary or sensitive data. This article demonstrates the standard methods for excluding specific files and directories when generating a tar archive. We cover command-line flags, wildcard patterns, and external exclude lists to streamline your backup process.
Using the –exclude Flag
The primary method involves adding the --exclude option
followed by the path you wish to omit. You must specify this option
before the files or directories you are archiving.
tar --exclude='/path/to/file.log' -czvf backup.tar.gz /path/to/sourceExcluding Multiple Items
You can stack multiple --exclude flags to skip several
files or folders in a single command.
tar --exclude='/path/to/cache' --exclude='/path/to/temp' -czvf backup.tar.gz /path/to/sourceUsing Wildcard Patterns
To exclude files based on extensions or naming patterns, use wildcards. Ensure the pattern matches the relative path structure.
tar --exclude='*.log' --exclude='*.tmp' -czvf backup.tar.gz /path/to/sourceUsing an Exclude File
For complex lists, create a text file containing one exclude pattern
per line. Use the --exclude-from flag to reference this
list.
- Create a file named
excludes.txt:
*.log
/path/to/secret
- Run the tar command:
tar --exclude-from=excludes.txt -czvf backup.tar.gz /path/to/sourceVerifying the Archive
After creation, list the contents of the archive to confirm the excluded files are absent.
tar -tzvf backup.tar.gzThis ensures your backup contains only the intended data without unnecessary bloat.