Blog about Web Programming and Electronics
💬 👤
back Back to blog
Linux

How tar Works

The tar command (tape archive) is a tool for bundling files into a single archive file and compressing them. It originated in the days when data was stored on magnetic tapes, but today it is the standard tool for backups and transferring projects on Linux.

tar -czvf archive.tar.gz folder/

What Is tar

tar combines multiple files and directories into a single file — an archive. It does not compress by itself, but uses external programs for compression: gzip (extension .tar.gz) or bzip2 (extension .tar.bz2). That is why tar is often called a "wrapper" that contains compressed data.

Creating an Archive

The most common combination of flags is -czvf: c creates the archive, z compresses with gzip, v shows progress, and f means the file name follows.

tar -czvf project.tar.gz project/ # creates a compressed archive of a folder
tar -cvf archive.tar folder/ # archive without compression

Extracting an Archive

To extract we use the flag x (extract). Before extracting, it is worth checking what is inside the archive, so it does not unpack into the wrong directory.

tar -tzf archive.tar.gz # lists the contents of the archive
tar -xzvf archive.tar.gz # extracts into the current directory
tar -xzvf archive.tar.gz -C /tmp # extracts into the /tmp directory

Adding and Deleting Files

We can append files to an existing (uncompressed) archive with the flag r and delete them with --delete.

archive="archive.tar"
tar -rvf archive.tar new.txt # appends a file to the archive
tar -f archive.tar --delete old.txt # deletes a file from the archive

Comparison with the zip Format

The zip format bundles and compresses in one step, while tar separates archiving from compression. That is why .tar.gz is common on Linux and .zip on Windows. Both formats of course work everywhere — the difference is only in convention and compression ratio.

With three commands — create, list, extract — you cover most everyday tasks. Any further option can always be looked up with the command man tar.

back Back to blog