This reference page gathers the tar commands you need to know: create an
archive with tar -czvf, list its content with tar -tvf, extract it with
tar -xzvf, exclude files or transfer a directory over SSH without an
intermediate file. Each option is explained and each example was validated with
GNU tar. It is aimed at administrators and developers who manage
backups, compress logs or prepare deliveries to transfer. Keep it as a
cheat sheet: the basic syntax first, then the practical cases (dated backup,
incremental, automation with cron) and the troubleshooting of classic
errors.
What you will learn
- Create an archive with or without compression (gzip, bzip2, xz);
- List the content of an archive and extract all or part of its files;
- Exclude files from an archive and avoid tarbombs;
- Automate dated or incremental backups;
- Diagnose the common errors of
tar.
What is tar?
The tar command, short for tape archive, was originally designed to back up files on magnetic tapes. Today, it remains a pillar of Unix/Linux systems to group several files or directories into a single archive, while keeping their permissions, dates, structure and owners.
Its big advantage? It works with or without compression, it can list or extract specific files without decompressing the whole archive, and it fits in scripts, automated tasks or network transfers.
Here are a few concrete cases where tar is useful:
- Back up the content of a directory before an update;
- Compress log files that have grown too large;
- Transfer a complete project to another server over SSH;
- Prepare repositories or packages for a deployment.
It is therefore unavoidable as soon as you talk about file management at scale or system scripting.
Basic syntax
The tar command follows a simple but powerful structure. It is made of options, the name of the archive and the files or directories to process.
tar [options] [nom_archive] [fichiers_ou_dossiers]Here are the main options to know:
-c: creates a new archive (create)-x: extracts an archive (extract)-t: shows the content of an archive (list)-f: sets the archive file to use (file), always last among the options-v: verbose mode, prints the files processed (verbose)-z: uses gzip for compression/decompression-j: uses bzip2-J: uses xz
Usage examples:
-
Create an archive:
Terminal window tar -cvf archive.tar mon_dossier/ -
Create an archive compressed with gzip:
Terminal window tar -czvf archive.tar.gz mon_dossier/ -
Extract an archive:
Terminal window tar -xvf archive.tar
Note: the order of the options matters, above all for -f, which must come
immediately before the name of the archive file. A
tar -cfzv archive.tar.gz dossier/ creates a file named zv instead of the
expected archive: -f consumed the following letters as a file name.
Once you master this basic syntax, you can move on to more advanced use cases: excluding files, automatic backups, transfers, and more.
Creating archives
Creating an archive with tar is a frequent operation, whether to make a backup, transfer a complete directory or simply group files together. Here are the most common forms.
Without compression
This command creates a .tar archive containing every file of a directory:
tar -cvf archive.tar mon_dossier/-c: creation-v: prints the archived files-f: gives the name of the archive
With gzip compression
Gzip is the most widespread compression format with tar. It is fast and well
supported:
tar -czvf archive.tar.gz mon_dossier/-z: gzip compression
With bzip2 compression
Bzip2 compresses better than gzip, but it is slower. Useful for long-term archives.
tar -cjvf archive.tar.bz2 mon_dossier/-j: bzip2 compression
With xz compression
XZ offers the best compression, but it is also the slowest.
tar -cJvf archive.tar.xz mon_dossier/-J: xz compression
Recent versions of GNU tar also accept --zstd. At its default level,
zstd compresses about as well as gzip but much faster: measured on Debian
13 with 40 MB of Python code, the archive weighs 10.7 MB in 0.18 s, against
11.0 MB in 1.1 s for gzip and 7.8 MB in 7.6 s for xz:
tar --zstd -cvf archive.tar.zst mon_dossier/Archiving several files
You can also target several files at once:
tar -czvf mes_fichiers.tar.gz fichier1.txt fichier2.log dossier/Tip: to exclude some files or directories when creating an archive, you can
use the --exclude option:
tar --exclude='*.log' -czvf archive.tar.gz mon_dossier/Creating an archive suited to your need, with or without compression, is the
first step towards using tar efficiently.
Extracting archives
Extracting an archive is just as important as creating it. Whether you want to recover a whole backup or only a specific file, tar offers great flexibility.
Simple extraction (without compression)
To extract the content of a .tar archive:
tar -xvf archive.tar-x: extraction-v: verbose mode-f: file to extract
Extraction with compression
The compression options match the format of the archive:
-
.tar.gzor.tgz:Terminal window tar -xzvf archive.tar.gz -
.tar.bz2:Terminal window tar -xjvf archive.tar.bz2 -
.tar.xz:Terminal window tar -xJvf archive.tar.xz
Good to know: when reading (extraction or listing), GNU tar detects the
compression automatically. A simple tar -xvf archive.tar.gz therefore works
without -z. The compression option remains essential at creation of the
archive, though.
Extracting to a specific directory
Rather than extracting into the current directory, you can set a destination
directory with the -C option. Put it before the file names or the
patterns to extract: written after them, it is ignored without any error
and the files land in the current directory (observed with GNU tar 1.35):
tar -xvf archive.tar -C /chemin/vers/dossier/Extracting one or more specific files
If you do not want to extract everything, you can target one or more precise files:
tar -xvf archive.tar chemin/vers/fichier.txtOr several files at once:
tar -xvf archive.tar fichier1.txt fichier2.logCareful: the path must match exactly the one shown by
tar -tf archive.tar, otherwise tar returns Not found in archive.
Using wildcards
To extract only certain types of files:
tar -xvf archive.tar --wildcards '*.jpg'This is very handy to recover only the images, the .sh scripts, or any
other specific format. The single quotes around the pattern matter: they
prevent the shell from interpreting *.jpg before tar.
The pattern applies to the path stored in the archive, not only to the file name: you can therefore restrict it to a specific subdirectory.
tar -xvf archive.tar --wildcards 'logs/*.log'The --wildcards option is not decorative. Without it, the tar of
Debian 13 answers Pattern matching characters used in file names then
Not found in archive, whereas that of AlmaLinux 10, patched by Red Hat,
accepts the pattern. Always write it so that a script stays portable.
With these commands, you gain real control over what you extract, where and how. It is fundamental in a production environment or for a targeted recovery of data.
Handling archives
Tar is not limited to creating or extracting: you can also analyse, modify or complete an existing archive. These advanced functions let you adjust an archive without starting from scratch.
Listing the content of an archive
Before extracting, it is often useful to see what it contains:
tar -tvf archive.tar-t: lists the content without extracting-v: shows permissions, sizes, dates, etc.
With a compressed archive:
tar -tzvf archive.tar.gzAdding files to an archive
You can add files, but only if the archive is not compressed:
tar -rvf archive.tar nouveau_fichier.txt-r: append, adds to the archive
Add a complete directory:
tar -rvf archive.tar nouveau_dossier/On a compressed archive, the same command fails with the explicit message
tar: Cannot update compressed archives. You must then recreate the archive
or work on an uncompressed .tar.
Deleting files from an archive (with --delete)
Careful: this function only works on uncompressed archives:
tar --delete -f archive.tar chemin/vers/fichierReading a damaged archive
Faced with a truncated archive (interrupted transfer, full disk), tar
extracts what it can up to the cut-off point, then stops with
tar: Unexpected EOF in archive. The files located before the corruption are
recovered; those after it are lost.
The --ignore-zeros option can help when the archive contains null
blocks in the middle (concatenated archives or zeroed areas): it forces
tar to keep reading instead of treating these blocks as the end of the
archive:
tar -xvf archive.tar --ignore-zerosIt is not a repair tool: nothing rebuilds the missing data. The real
safeguard remains a checksum (sha256sum) verified after each
transfer.
Practical cases
To really master the tar command, nothing beats a few concrete scenarios.
Here are examples of everyday use in a system or DevOps environment.
Full backup of a directory
To archive a whole directory, including its subdirectories and permissions:
tar -czvf sauvegarde_$(date +%Y%m%d).tar.gz /etc/This creates an archive named after the current date, useful for daily backups.
Incremental backup (with --listed-incremental)
Create a state file to back up only what changed since the last backup:
tar --listed-incremental=etat.snar -czvf backup.tar.gz /home/user/On the first run, the state file etat.snar does not exist yet: tar
makes a full backup and creates it. On the following runs, with the same
state file but a new archive name, only the modified files are archived. To
restore, you must replay the full backup then each incremental one in order.
Transferring a directory over SSH
To send a directory to a remote server without storing it locally:
tar -czf - mon_dossier/ | ssh user@serveur 'tar -xzf - -C /destination/'This method is fast and avoids temporary files: the - asks tar to write
the archive to standard output, which SSH carries to the remote
tar -x.
Compressing and cleaning up logs
Archive and delete the .log files older than 7 days:
find /var/log -name "*.log" -mtime +7 -print | tar -czvf logs_ancien.tar.gz -T - --remove-filesThe -T - option reads the list of files from standard input (the one
produced by find), and --remove-files deletes each file after
archiving it. Test it first without --remove-files: one find pattern error
and the wrong files disappear.
Automating a backup with cron
Example of a line to insert in a crontab to make a backup every night at 2 am:
0 2 * * * tar -czf /sauvegardes/backup_$(date +\%Y\%m\%d).tar.gz /home/utilisateur/The % characters are escaped as \% because this character has a special
meaning in a crontab (end of command). This command can also be
integrated into a script with an email notification, an upload to a cloud,
etc.
Integration with find to target files
Create an archive with every file modified in the last 2 days:
find . -type f -mtime -2 -print | tar -czvf modifs.tar.gz -T -These use cases let you move from occasional use to robust automation, suited to professional use.
Good practices
Mastering the tar command also means adopting reliable habits to avoid errors, improve readability and ease maintenance.
Always check the content before extraction
Before extracting an archive, above all if it is large or unknown:
tar -tvf archive.tar.gzThis avoids overwriting important files or polluting a directory with unexpected files.
Using dedicated directories
An archive that extracts files directly into the current directory is called a tarbomb. To avoid it, always archive a root directory:
tar -czvf mon_projet.tar.gz mon_projet/And for the extraction:
mkdir test && tar -xvf archive.tar -C test/Choosing the right compression
The four algorithms trade speed against size, and the measurement quoted above sums up the trade-off: a few tenths of a second for zstd, about eight seconds for xz on the same 40 MB of text.
- gzip: fast, supported everywhere, a good compromise
- bzip2: more compression, but slower
- xz: maximum compression, very slow, ideal for long-term archiving
- zstd: size close to gzip for a much higher speed, on recent systems
Adapt to your context: speed or minimum size?
Including the date in archive names
It is essential to find your way around backups:
tar -czvf backup_$(date +%Y%m%d).tar.gz /etc/Always putting -f last among the options
The order of the options matters. Always put -f just before the name of the
archive:
tar -czvf archive.tar.gz dossier/Avoiding common errors
Three mistakes come back again and again, and each of them is covered by one of the practices above.
- Forgetting
-fand getting a confusing error message - Trying to modify a compressed archive
- Extracting an archive at the root without checking its content
By following these practices, you avoid most classic pitfalls. You also gain readability, safety and efficiency, above all in automated scripts.
Troubleshooting
tar errors are almost always the same: an incorrect option order, a
forbidden operation on a compressed archive or a damaged archive. This
table sums up the most frequent symptoms and their fix.
| Symptom | Probable cause | Fix |
|---|---|---|
A zv file appears and tar prints Cannot stat: No such file or directory | -f is not the last option of the group (e.g. tar -cfzv) | Reorder: -f just before the name of the archive (tar -czvf) |
tar: Cannot update compressed archives | -r (append) or --delete on a .tar.gz archive | Work on an uncompressed .tar, or recreate the complete archive |
tar: Unexpected EOF in archive | Truncated archive (interrupted transfer, full disk) | Transfer the archive again; check with sha256sum; the files before the cut-off remain extractable |
| Files scattered in the current directory after extraction | Tarbomb: the archive has no root directory | List with tar -tf before extracting, then extract with -C into a dedicated directory |
Not found in archive during a targeted extraction | The requested path does not match the one stored in the archive | Copy the exact path shown by tar -tf archive.tar |
| Owners or permissions lost at extraction | Extraction run without privileges | Extract with sudo to restore the original owners |
Key points
- The three basic actions fit in three options:
-ccreates,-tlists,-xextracts;-fdesignates the archive and always comes last in the option group. - Compression is chosen at creation:
-z(gzip),-j(bzip2),-J(xz),--zstd; when reading, GNU tar detects it automatically. - Always list (
tar -tf) an unknown archive before extracting it, and extract with-Cinto a dedicated directory to avoid tarbombs. - A compressed archive cannot be modified:
-rand--deleterequire an uncompressed.tar. --excludefilters at creation,--wildcardsfilters at extraction: the single quotes around the pattern are mandatory.- Combined with
find,sshorcron,tarcovers the dated backup, the incremental one (--listed-incremental) and the transfer without a temporary file.
Knowledge check
Check that the essentials of this guide are acquired. The questions only cover what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: wget: download from the command line
A new full quiz with random questions
Work again only on the questions you missed
FAQ: frequently asked questions
The answers below go into more detail on compression, extraction and exclusions, with measurements taken on Debian 13.
Definition
tar (Tape ARchive) is an archiving tool that groups several files/directories into a single archive, preserving the tree and the metadata (permissions, timestamps, owner).| Characteristic | Description |
|---|---|
| Type | Native archiver, not a compressor |
| Format | Sequential concatenation of the files |
| Metadata | Preserves permissions, dates, links |
| Compression | Through a pipe (gzip, bzip2, xz) |
| Extensions | .tar, .tar.gz, .tgz, .tar.bz2, .tar.xz |
| Origin | Designed for tape backups (1979) |
Compression variants
# Without compression (raw archive)
tar -cf archive.tar dossier/
# With gzip (standard, fast)
tar -czf archive.tar.gz dossier/
# With bzip2 (better compression)
tar -cjf archive.tar.bz2 dossier/
# With xz (maximum compression)
tar -cJf archive.tar.xz dossier/
DevOps context: essential for deployments, application backups, source code transfers, building Docker images (tar layers).Reasons to use it
| Use case | Advantages | Example |
|---|---|---|
| Backup | Preserves structure + metadata | tar -czf backup-$(date +%F).tar.gz /var/www |
| Network transfer | 1 file instead of thousands | tar -czf - /app | ssh user@dest tar -xzf - |
| Deployment | Exact reproducibility | tar -xzf release-v1.2.tar.gz -C /opt |
| Archiving | Efficient compression | tar -cJf logs-2023.tar.xz /var/log |
| Versioning | Timestamped snapshots | tar -czf config-$(date +%s).tar.gz /etc |
Advantages over other tools
- vs cp: preserves complex permissions/owners
- vs zip: universal Linux format, better pipe integration
- vs rsync: static archiving (no synchronisation)
- vs dd: file granularity (not raw blocks)
# Incremental backup (with find)
find /var/www -type f -mtime -1 | tar -czf daily.tar.gz -T -
# Network pipeline (without an intermediate file)
tar -czf - /data | ssh backup tar -xzf - -C /backups
DevOps context: GitLab backups, CI/CD artifacts, LXC containers, Terraform state exports.General syntax
tar [MODE] [OPTIONS] [ARCHIVE] [FICHIERS...]
Main modes (exactly 1 required)
| Mode | Short option | Long option | Action |
|---|---|---|---|
| Create | -c |
--create |
Create an archive |
| eXtract | -x |
--extract |
Extract an archive |
| lisT | -t |
--list |
List the content |
| aPpend | -r |
--append |
Add files |
| Update | -u |
--update |
Update modified files |
Essential options
| Option | Meaning | Usage |
|---|---|---|
-f FILE |
Archive file | Required (otherwise stdin/stdout) |
-v |
Verbose | Prints the files processed |
-z |
gZip | .tar.gz compression/decompression |
-j |
bZip2 | .tar.bz2 compression |
-J |
XZ | .tar.xz compression |
-C DIR |
Change directory | Extraction into a specific directory |
-p |
Preserve permissions | Keeps exact permissions (useful as root) |
Annotated examples
# Creating a gzip archive
tar -czf backup.tar.gz /etc/nginx
# | | |
# | | +-> Archive name
# | +----> gZip
# +------> Create, File
# Verbose extraction
tar -xzvf backup.tar.gz -C /restore
# | | |
# | | +-> Archive name
# | +----> Verbose
# +-------> eXtract, gZip, File
Basic archive creation
# Minimal syntax
tar -cf archive.tar dossier/
# ||
# |+-> Archive file (name required with -f)
# +---> Create
Practical examples
# Archive of a directory
tar -cf backup.tar /var/www/html
# Archive several sources
tar -cf projet.tar src/ docs/ README.md
# Verbose (print the files processed)
tar -cvf backup.tar /etc/nginx
# Permissions are always recorded at creation
tar -cf system.tar /etc /opt
# -p only matters at extraction (implicit when root extracts)
Characteristics
| Property | Behaviour |
|---|---|
| Compression | None (raw archive) |
| Size | Sum of the files + metadata (~101% of the sources) |
| Speed | Fast (I/O only) |
| Metadata | Permissions, timestamps, links preserved |
| Modification | Possible (-r to append) |
Difference with tar.gz
# Measured on Debian 13: Python standard library, 40 MB of text
# WITHOUT compression (instant, large size)
tar -cf backup.tar data/ # 40.2 MB in 0.05 s
# WITH gzip compression (slower, smaller)
tar -czf backup.tar.gz data/ # 11.0 MB in 1.1 s
Usage: archives to complete incrementally, fast network transfers (pipe).Creation with gzip compression
# -z option for gzip
tar -czf archive.tar.gz dossier/
# |
# +-> gZip (compression)
# Verbose equivalent
tar -czvf backup.tar.gz /var/www
Compression variants
| Method | Command | Final size (measured) | Speed | Compatibility |
|---|---|---|---|---|
| gzip | tar -czf |
27% of the original | Fast | Universal |
| bzip2 | tar -cjf |
24% | Medium | Very good |
| xz | tar -cJf |
19% | Slow | Good (2009+) |
| zstd | tar --zstd -cf |
27% | Very fast | Recent systems |
Comparative examples
# Measured on Debian 13 (GNU tar 1.35): 40.2 MB of Python code, 667 files
# Without compression (40.2 MB, 0.05 s)
tar -cf data.tar data/
# gzip - standard (11.0 MB, 1.1 s)
tar -czf data.tar.gz data/
# bzip2 - better ratio than gzip (9.6 MB, 1.9 s)
tar -cjf data.tar.bz2 data/
# xz - maximum compression (7.8 MB, 7.6 s)
tar -cJf data.tar.xz data/
# zstd - gzip size, six times faster (10.7 MB, 0.18 s)
tar --zstd -cf data.tar.zst data/
These figures hold for text: on files that are already compressed (images, videos, .gz), no algorithm gains much.Good practices
# Naming convention
tar -czf backup-$(date +%F).tar.gz /data
# backup-2026-01-08.tar.gz
# Exclude large files
tar -czf archive.tar.gz --exclude='*.mp4' dossier/
# Custom compression level (1-9): pass the full command with -I
tar -I 'gzip -9' -cf max-compress.tar.gz /data
# GZIP=-9 still works but gzip 1.13 warns: deprecated variable
DevOps usage: daily backups, CI/CD artifacts, container exports.Basic extraction
# Extraction into the current directory
tar -xzf archive.tar.gz
# ||
# |+-> gZip (automatic decompression)
# +---> eXtract
# Verbose (see the extracted files)
tar -xzvf backup.tar.gz
Extraction options
| Option | Usage | Example |
|---|---|---|
-C DIR |
Extract into a specific directory | tar -xzf data.tar.gz -C /restore |
-p |
Preserve exact permissions | tar -xzpf system.tar.gz (root) |
--strip-components=N |
Remove N directory levels | tar -xzf app.tar.gz --strip-components=1 |
--keep-old-files |
Do not overwrite existing files | tar -xzf backup.tar.gz -k |
-v |
Verbose mode | Prints each extracted file |
Practical examples
# Extraction into /tmp
tar -xzf backup.tar.gz -C /tmp
# Extract preserving everything (root mode)
sudo tar -xzpf system-backup.tar.gz -C /
# Remove the root directory (app/src/* -> src/*)
tar -xzf release.tar.gz --strip-components=1
# Extract a specific file
tar -xzf archive.tar.gz chemin/vers/fichier.txt
# Extract a pattern (all the .conf files)
tar -xzf backup.tar.gz --wildcards '*.conf'
Checks before extraction
# List the content (without extracting)
tar -tzf archive.tar.gz
# Count the files
tar -tzf backup.tar.gz | wc -l
# Check integrity
gunzip -t backup.tar.gz
Security: always list before extracting (risk of absolute paths, path traversal).Basic listing
# List files (uncompressed tar)
tar -tf archive.tar
# |
# +-> lisT (show the content)
# List a tar.gz
tar -tzf archive.tar.gz
# |
# +-> gZip
# With details (permissions, size, date)
tar -tvf backup.tar
# |
# +-> Verbose (long format)
Output formats
# Simple output (paths only)
$ tar -tzf backup.tar.gz
app/
app/config.yml
app/main.py
# Detailed output (ls -l style)
$ tar -tvzf backup.tar.gz
drwxr-xr-x user/group 0 2026-01-08 10:12 app/
-rw-r--r-- user/group 452 2026-01-08 10:12 app/config.yml
-rwxr-xr-x user/group 8743 2026-01-08 10:12 app/main.py
Filtering and searching
# Look for a specific file
tar -tzf archive.tar.gz | grep config
# Count the files
tar -tzf backup.tar.gz | wc -l
# List only the .py files
tar -tzf app.tar.gz | grep '\.py$'
# Total uncompressed size
tar -tvzf backup.tar.gz | awk '{sum+=$3} END {print sum/1024/1024 "Mo"}'
Security checks
# Detect absolute paths (risk of overwriting)
tar -tzf suspect.tar.gz | grep '^/'
# Detect path traversal
tar -tzf suspect.tar.gz | grep '\.\.'
# Analyse the structure
tar -tzf archive.tar.gz | cut -d/ -f1 | sort -u
DevOps context: validating CI/CD artifacts, auditing backups, checking releases.Incremental addition
# -r option (append)
tar -rvf archive.tar nouveau_fichier.txt
# ||
# |+-> Verbose (optional)
# +---> aPpend (add)
# Add several files
tar -rvf backup.tar docs/ config.yml
Important limitations
| Constraint | Reason | Solution |
|---|---|---|
| Compressed archives | Incompatible (-r refuses .tar.gz) | Decompress → add → recompress |
| Position | Added at the end of the archive | Use -A to concatenate |
| Size | The archive grows linearly | Recreate it periodically |
Workflow for compressed archives
# Method 1: decompress temporarily
gunzip backup.tar.gz # backup.tar
tar -rvf backup.tar new_file.txt # Addition
gzip backup.tar # backup.tar.gz
# Method 2: full extraction + recreation
mkdir temp && tar -xzf backup.tar.gz -C temp
cp new_file.txt temp/
tar -czf backup.tar.gz -C temp .
# Method 3: concatenating archives (both uncompressed)
tar -cf addon.tar new_files/
tar -Af main.tar addon.tar # Adds the content of addon.tar to main.tar
Modern alternatives
# Incremental backup with find
find /data -type f -newer /tmp/last_backup.stamp | \
tar -czf incremental.tar.gz -T -
touch /tmp/last_backup.stamp
# Versioning (create a new archive)
tar -czf backup-$(date +%Y%m%d-%H%M).tar.gz /data
Good practice: prefer new timestamped archives over appending to large archives.Targeted extraction
# Extract 1 file (exact path)
tar -xzf archive.tar.gz chemin/vers/fichier.txt
# Extract several files
tar -xzf backup.tar.gz file1.conf file2.log
# Extract with a pattern (wildcards)
tar -xzf archive.tar.gz --wildcards '*.conf'
Find the exact path
# List to identify the path
tar -tzf archive.tar.gz | grep config
# Extraction with result
tar -xzvf backup.tar.gz app/config/database.yml
Extraction with filters
| Method | Example | Usage |
|---|---|---|
| Pattern without option | tar -xzf data.tar.gz '*.json' |
Accepted on RHEL (patched tar), refused on Debian: Not found in archive |
| Wildcards | tar -xzf backup.tar.gz --wildcards 'logs/2026-*' |
Complex pattern |
| Whole directory | tar -xzf archive.tar.gz app/config/ |
Complete directory |
| Exclusion | tar -xzf data.tar.gz --exclude='*.tmp' |
Reverse the selection |
Practical examples
# Extract every .conf file of a system backup
# -C BEFORE the pattern: placed after it, it is ignored without error
tar -xzf system.tar.gz -C /tmp --wildcards '*.conf'
# Restore only /etc/nginx
tar -xzf full-backup.tar.gz etc/nginx
# Extract while rewriting the path
tar -xzf app.tar.gz app/config.yml --strip-components=1
# Result: config.yml (without the app/ directory)
# Multiple targeted extraction
tar -xzf backup.tar.gz \
etc/nginx/nginx.conf \
etc/ssl/private/server.key
Tip: always list (-t) before extracting to check the exact paths.Simple exclusions
# Exclude a pattern (.log files)
tar --exclude='*.log' -czf backup.tar.gz /var/www
# Exclude several patterns
tar --exclude='*.tmp' --exclude='*.cache' -czf clean.tar.gz /app
# Exclude a whole directory
tar --exclude='node_modules' -czf projet.tar.gz /projet
Advanced exclusions
| Method | Syntax | Usage |
|---|---|---|
| Simple pattern | --exclude='*.log' |
Specific extension |
| Directory | --exclude='cache' |
Directory name anywhere |
| Absolute path | --exclude='/var/cache' |
Precise location |
| List file | --exclude-from=exclusions.txt |
Multiple patterns |
| VCS repositories | --exclude-vcs |
Exclude .git, .svn automatically |
Exclusions file
# Create a list of exclusions
cat > exclusions.txt <<EOF
*.log
*.tmp
node_modules
.git
__pycache__
*.pyc
EOF
# Use the list
tar --exclude-from=exclusions.txt -czf clean.tar.gz /projet
Common DevOps patterns
# Code backup without dependencies
tar --exclude='node_modules' \
--exclude='vendor' \
--exclude='.git' \
-czf code-only.tar.gz /app
# Backup with multiple exclusions
tar --exclude='*.log' \
--exclude='*.tmp' \
--exclude='cache/*' \
--exclude-vcs \
-czf production.tar.gz /var/www
# Exclude large files (>100M)
tar --exclude-from=<(find /data -size +100M) \
-czf data-light.tar.gz /data
The --exclude-vcs option
# Excludes automatically
tar --exclude-vcs -czf projet.tar.gz /code
# Ignores, among others: .git, .svn, .hg, .bzr, CVS
Tip: after creation, check the exclusion with tar -tzf archive.tar.gz | grep motif, which must return nothing.