Linux online course

Using tar to Bundle, Compress, and Extract Files in Linux

Learn how to use Linux tar to create, compress, inspect, selectively extract, and safely unpack archives while preserving paths and metadata.

tar is a Linux command-line utility for collecting multiple files and directories into one portable file. You can use it to package files for transfer, create source distributions, make backups, or unpack software downloaded as a tarball.

A tar archive normally preserves the stored directory structure and commonly preserves metadata such as permissions and timestamps. By itself, tar combines files but does not reduce their size. Compression is an additional step performed by gzip, bzip2, xz, or another supported compressor.

What tar does

The name tar comes from “tape archive,” but modern tar is commonly used with ordinary files, disks, and network transfers. It combines filesystem entries into one archive, often called a tar file or tarball.

  • A plain tar file contains bundled entries but has no compression.
  • A compressed tarball contains the tar archive plus a compression layer.
  • Including a directory normally includes that directory and all nested files and subdirectories.
  • The stored paths retain their directory relationships, so an archive can recreate the same tree during extraction.

Compression means reducing the size of data with a compressor. Compression does not replace tar: tar packages the entries, while gzip, bzip2, or xz compresses the resulting archive stream.

Tarball naming conventions

File suffixes conventionally describe the archive and compression method. The suffix is useful documentation, but it does not force tar to use that method. The operation flags determine what tar actually does, and a file may have been renamed incorrectly.

Typical suffixCompression methodCreation optionExtraction consideration
.tarNoneNo compression optionUse tar -xvf
.tar.gz or .tgzgzip-zUse -xzf, or automatic detection where available
.tar.bz2bzip2-jUse -xjf, or automatic detection where available
.tar.xzxz-JUse -xJf, or automatic detection where available
.tar.zstzstd, where supportedSupport varies by tar versionCheck the local tar manual and installed compressor support

gzip is usually a good general-purpose choice because it is widely available and reasonably fast. bzip2 often compresses better than gzip but is slower. xz commonly provides stronger size reduction, especially for source code and text, but usually takes more time and memory. Already-compressed files such as JPEG images, videos, and many package files may shrink very little.

Basic tar command structure

The general form is:

tar [operation/options] -f output-file input-paths

The operation tells tar what to do, such as create, extract, or list. The -f option specifies the tar file to create or read. Its argument must be the archive filename, so place the filename immediately after -f when using the common form. Source files and directories come after the options and archive filename.

For example, in tar -cvf archive.tar results.txt sample_text, -c creates an archive, -v prints names, -f archive.tar selects the output file, and the final two paths are the inputs.

Common operations and options

OptionMeaningTypical use
-cCreate a new tar filePackage files and directories
-xExtract filesUnpack an archive
-tList contentsInspect stored paths without extracting
-vVerbose outputDisplay processed names and detailed listing information
-fSpecify the tar fileChoose the archive to create, read, or extract
-zUse gzipCreate or extract a gzip-compressed tarball
-jUse bzip2Create or extract a bzip2-compressed tarball
-JUse xzCreate or extract an xz-compressed tarball
-CUse a destination directoryExtract somewhere other than the current directory
--excludeOmit matching pathsLeave caches, logs, or generated directories out

Creating tar files

Create an uncompressed archive

Give -c, the archive filename with -f, and the files to include:

tar -cvf archive.tar results.txt sample_text

This creates archive.tar containing results.txt and sample_text. The verbose option prints each name as tar adds it. Without -v, tar normally performs the operation without printing every entry.

Create a gzip-compressed tarball

tar -czvf compress.tgz results.txt sample.txt

Here, -z applies gzip compression. The equivalent longer suffix is commonly compress.tar.gz.

Archive a directory

tar -czvf project.tar.gz project/

This includes project/ and its nested contents. If the directory contains subdirectories, regular files, or normally accessible metadata, those entries are included in the archive.

Exclude unwanted content

tar -czvf source.tar.gz --exclude='node_modules' --exclude='*.log' source/

--exclude prevents matching paths from being added. Quote patterns such as *.log so the current shell does not expand them before tar receives them. Check the result with a listing command because matching behavior can depend on the stored path and local tar implementation.

Inspecting an archive

Use -t to list stored paths without extracting anything:

tar -tvf archive.tar
tar -tzvf project.tar.gz

The first command lists an uncompressed archive. The second lists a gzip-compressed tarball. With -v, tar displays details such as permissions, ownership, size, timestamps, and names.

Inspecting unfamiliar contents before extraction is an important safety habit. It helps you find the top-level directory, identify unexpected files, and notice paths that could collide with existing files.

Extracting archives safely

Extract into the current directory

tar -xzvf compress.tgz

This extracts the gzip-compressed archive into the current working directory. Unless you specify another destination, tar writes relative to the directory shown by pwd.

Extract into a chosen destination

tar -xzvf project.tar.gz -C /path/to/destination

The destination directory should already exist. Create it first when necessary, then use -C to tell tar where extraction should occur. Extracting into a new, empty directory reduces the chance of overwriting unrelated files.

Extract one member

tar -xzvf project.tar.gz project/README.md

Only the stored member named project/README.md is extracted. The path must exactly match the path shown by tar -tf or tar -tzf; a path beginning with ./, a missing directory prefix, or different capitalization will not match.

Extraction can overwrite existing paths when archive members have the same names as files in the destination. List the archive first and choose a controlled destination when the source is unfamiliar.

Compression and decompression flags

  • -z selects gzip, commonly used with .tar.gz and .tgz.
  • -j selects bzip2, commonly used with .tar.bz2.
  • -J selects xz, commonly used with .tar.xz.

Modern GNU tar can often detect compression automatically while extracting. Explicit flags remain useful because they document the expected format and work consistently across environments. When creating an archive, specify the compression option; changing only the filename suffix does not compress the data.

Understanding compact option forms

Traditional tar syntax allows operation letters to be combined:

  • tar -cvf archive.tar files: create, be verbose, and use the named file.
  • tar -czvf archive.tar.gz files: create with gzip compression, be verbose, and use the named file.
  • tar -xzvf archive.tar.gz: extract gzip-compressed content, be verbose, and use the named file.

Option letters may be combined because they are short flags. The important exception in these examples is -f: it needs a following archive filename. Do not accidentally make a source path the argument to -f.

A practical create, inspect, and extract workflow

  1. Move to the directory containing the material and confirm it with pwd and ls.
  2. Create the archive, selecting compression if appropriate.
  3. List the archive contents and check that expected paths are present and unwanted paths are absent.
  4. Send or store the archive only after reviewing its contents.
  5. For extraction, create a separate destination, list the archive again if it is unfamiliar, and extract with -C.
tar -czvf project.tar.gz project/
tar -tzvf project.tar.gz
mkdir -p /tmp/unpacked-project
tar -xzvf project.tar.gz -C /tmp/unpacked-project

This workflow creates a gzip tarball, inspects its detailed listing, creates an extraction directory, and unpacks the archive there.

Troubleshooting tar commands

tar cannot open the named archive

Check whether the filename or path is wrong, whether you are in a different directory, or whether you lack read permission:

ls -l archive.tar.gz
pwd

Use the correct relative or absolute path. Permission details from ls -l can reveal whether your user can read the archive.

Files appear in an unexpected location

Tar extracts into the current working directory unless -C is used. Run pwd, change to the intended directory with cd, or provide an explicit destination with -C.

A selected member cannot be found

The requested member path probably does not exactly match the stored path. List the archive first and copy the displayed path:

tar -tf archive.tar
 tar -tzf project.tar.gz

Remove the accidental leading space before the second command when typing it; it is shown only as a separate example line.

The compression option does not match the file

A gzip flag cannot read bzip2 data, and a misleading suffix may hide the actual format. Identify the file with:

file filename

Then use the matching option, or use a compatible GNU tar version that can detect compression during extraction.

Existing files are replaced

Inspect with tar -t first and extract into a new empty directory with -C. For unusual overwrite requirements, consult the manual installed on your system with man tar.

The archive is larger than expected

You may have created a plain tar file, included caches or dependencies, or selected files that were already compressed. Use gzip, bzip2, or xz where suitable, add --exclude patterns for generated content, and inspect the member list with tar -t.

Exam-relevant notes

  • -c creates, -x extracts, and -t lists.
  • -v means verbose output; it does not enable compression.
  • -f identifies the archive filename and requires that filename as its argument.
  • -z, -j, and -J select gzip, bzip2, and xz respectively.
  • A .tar file is not necessarily compressed; .tar.gz and similar names conventionally indicate compression.
  • Use the exact stored path from a listing when extracting one member.
  • Use -C to control the extraction destination and inspect unfamiliar archives before unpacking them.

For related command-line skills, review determining file types, searching text with grep, and Bash command syntax.