Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

tar: create and extract a tar.gz archive

By updated

Improve this page

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.

Terminal window
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:

Terminal window
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:

Terminal window
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.

Terminal window
tar -cjvf archive.tar.bz2 mon_dossier/
  • -j: bzip2 compression

With xz compression

XZ offers the best compression, but it is also the slowest.

Terminal window
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:

Terminal window
tar --zstd -cvf archive.tar.zst mon_dossier/

Archiving several files

You can also target several files at once:

Terminal window
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:

Terminal window
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:

Terminal window
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.gz or .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):

Terminal window
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:

Terminal window
tar -xvf archive.tar chemin/vers/fichier.txt

Or several files at once:

Terminal window
tar -xvf archive.tar fichier1.txt fichier2.log

Careful: 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:

Terminal window
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.

Terminal window
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:

Terminal window
tar -tvf archive.tar
  • -t: lists the content without extracting
  • -v: shows permissions, sizes, dates, etc.

With a compressed archive:

Terminal window
tar -tzvf archive.tar.gz

Adding files to an archive

You can add files, but only if the archive is not compressed:

Terminal window
tar -rvf archive.tar nouveau_fichier.txt
  • -r: append, adds to the archive

Add a complete directory:

Terminal window
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:

Terminal window
tar --delete -f archive.tar chemin/vers/fichier

Reading 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:

Terminal window
tar -xvf archive.tar --ignore-zeros

It 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:

Terminal window
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:

Terminal window
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:

Terminal window
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:

Terminal window
find /var/log -name "*.log" -mtime +7 -print | tar -czvf logs_ancien.tar.gz -T - --remove-files

The -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:

Terminal window
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:

Terminal window
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:

Terminal window
tar -tvf archive.tar.gz

This 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:

Terminal window
tar -czvf mon_projet.tar.gz mon_projet/

And for the extraction:

Terminal window
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:

Terminal window
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:

Terminal window
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 -f and 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.

SymptomProbable causeFix
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 archiveWork on an uncompressed .tar, or recreate the complete archive
tar: Unexpected EOF in archiveTruncated 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 extractionTarbomb: the archive has no root directoryList with tar -tf before extracting, then extract with -C into a dedicated directory
Not found in archive during a targeted extractionThe requested path does not match the one stored in the archiveCopy the exact path shown by tar -tf archive.tar
Owners or permissions lost at extractionExtraction run without privilegesExtract with sudo to restore the original owners

Key points

  • The three basic actions fit in three options: -c creates, -t lists, -x extracts; -f designates 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 -C into a dedicated directory to avoid tarbombs.
  • A compressed archive cannot be modified: -r and --delete require an uncompressed .tar.
  • --exclude filters at creation, --wildcards filters at extraction: the single quotes around the pattern are mandatory.
  • Combined with find, ssh or cron, tar covers 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

6 questions
6 min
70% to pass

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

FAQ: frequently asked questions

The answers below go into more detail on compression, extraction and exclusions, with measurements taken on Debian 13.

Is this project useful to you?

The guides, courses, quizzes and labs stay free. If you use them regularly, you can contribute to their upkeep and development.

Become a supporting member (new tab) One-time support (new tab) Learn more

Follow the project on LinkedIn