Linux command line, archiving and compression: tar, gzip, bzip2, xz, zstd, zip, 7z, and rar commands
Greetings!

In this article, we will study ways to archive and compress files in Linux systems. I will explain how to use the utilities from the article title. There will be many examples, so please continue reading.

If you are new to the Linux world, I recommend studying my previous command-line articles:

Introduction

I separate these two procedures for a reason. Archiving is the process of combining several files into one, and it may not include compression at all. However, in practice, the resulting archive is almost always compressed to save disk space.

At some point while studying Linux, it was a revelation to me that tar is specifically an archiver. For compression, it uses external utilities usually named after the compression format: gzip, bzip2, xz, or zstd. Of course, there are many more formats, but in my experience these are used most often.

The zip and 7z utilities are worth mentioning separately: they can both archive and immediately compress data into their own eponymous format.

For Linux users who regularly deal with Windows, there is the rar utility (available in standard non-free repositories). It is proprietary software, but the open source utility unrar is used to extract archives.

All examples in the article were performed in the Linux Mint 22 (Ubuntu 24.04) distribution environment.

This concludes the introduction. Let’s move on to the list of commands we will examine.

Command list

So, today our tool arsenal will be expanded with the following archiver commands:

UtilityFull nameWhat it doesExtensionFeatures
tarTape ARchiveArchiving.tarOpen source. An archiver that only combines files and uses external utilities (gzip, bzip2, xz, zstd) for compression.
7z7zipArchiving + compression.7zOpen source. A universal format that archives and compresses very well at the same time.
zipEnglish zip (“compress”)Archiving + compression.zipOpen source. A universal format that archives and compresses simultaneously; a Windows standard.
rarRoshal ARchiverArchiving + compression.rarProprietary software. Also popular in Windows, with good compression but license restrictions; unrar is more often used for extraction in Linux.

And compression utility commands:

UtilityFull nameWhat it doesExtensionFeatures
gzipGNU ZipCompression.gzOpen source. Fast compression and extraction, widely used with tar for .tar.gz.
bzip2Burrows–Wheeler zip 2Compression.bz2Open source. Provides better compression than gzip but works more slowly.
xzsimply xz (based on LZMA2)Compression.xzOpen source. Provides maximum compression but is very slow during archiving and extraction.
zstdZstandardCompression.zstOpen source. A modern algorithm with an excellent balance of speed and compression quality.

For a rough understanding of the differences between formats, a subjective comparison of their operation and compression speed is shown below:

Format/commandCompression algorithm(s)Compression speedExtraction speedCompression ratio
gzipDeflatehighhighmedium
bzip2Burrows-Wheeler transform (BWT)lowmediumhigh
xzLZMA2lowlowvery high
zstdLZ77 and ANSvery highvery highvery high
zipDeflate and othersmediumvery highmedium
7zLZMA and othersmediumhighvery high
rarPPMdmediumhighhigh

The article focuses on the tar archiver plus compression utilities, because this combination is most often used for working with archives in Linux, including in Shell scripts. But I will also show basic commands for working with zip, 7z, and rar at the end of the article.

Preparation

tar and the gzip compression utility are almost always preinstalled in the system, unlike other archivers/utilities. If something required is missing from your system, you can always install it:

BASH
sudo apt update

sudo apt install -y tar gzip bzip2 xz-utils zstd zip 7z rar
Click to expand and view more

Before starting, create several files in the current directory to make the command examples more visual:

BASH
dd if=/dev/urandom of=./file1 bs=50K count=10

dd if=/dev/urandom of=./file2 bs=50K count=10

mkdir -v ./dir/

cp -v ./file1 ./file2 ./dir/
Click to expand and view more

Done, move on to creating archives.

Archiving with tar

Since tar is a fairly old program, it supports options in the classic Unix style, that is, without a hyphen before the option. To avoid confusing the reader, I will use the hyphenated options typical today😌.

So, the main tar commands.

Syntax:

BASH
tar [options] <archive_name> <files_or_directories>
Click to expand and view more

To avoid syntax errors, which beginners often encounter, you need to understand that the Linux command line operates with three types of parameters: flags: -f1 --flag2, named parameters: --arg value, and positional arguments: arg1 arg2 arg3. Confusion arises when parameters are combined, for example flags with named parameters; in that case, their order matters.

Source: betterdev.blog

Keeping this information in mind, proceed to studying tar commands.

Create an archive:

BASH
tar -c -f ./archive.tar ./file1 ./file2 ./dir/
Click to expand and view more

The command creates the arhcive.tar archive with the files/directory listed at the end in the current directory.

The typical extension for tar archives is .tar.

With the -v (--verbose) flag added, tar will print the files added to the archive line by line:

BASH
tar -v -c -f ./archive.tar ./file1 ./file2 ./dir/
Click to expand and view more

To change the path from which files should be taken for adding to the archive, use the -C or --directory option.

For example, the following command will add all files from the /tmp/dir/ directory to the archive:

BASH
cp -r ./dir/ /tmp/

tar -C /tmp/dir/ -c -f ./archive.tar ./
Click to expand and view more

The relative path ./ specified at the end tells tar to add all files from the current directory, which we changed with -C (/tmp/dir/ in the example above), to the archive.

It is important to understand that tar writes the file path to the archive exactly as it was passed: relative paths are preserved, and absolute ones only if explicitly allowed (--absolute-names). By default, / at the beginning of the path is removed. The same directories and files are created during extraction.

Extract an archive:

BASH
tar -x -f ./archive.tar
Click to expand and view more

-x (--extract) means extract, -f is the archive name.

This command extracts archive.tar into the current directory.

To change the directory into which the archive should be extracted, also use the -C or --directory option:

BASH
tar -C /tmp/dir/ -x -f ./archive.tar
Click to expand and view more

View contents:

BASH
tar -t -f ./archive.tar
Click to expand and view more

-t (--list) prints contents as a list, -f is the archive name.

By the way, the -t option is usually used to check an archive for damage to the file structure. Example:

BASH
tar -t -f ./archive.tar &> /dev/null
Click to expand and view more

If the archive is damaged, the command will exit with an error.

Add a file to an existing archive:

BASH
tar -r -f ./archive.tar /etc/passwd
Click to expand and view more

Check:

BASH
tar -t -f ./archive.tar
Click to expand and view more

As we can see, tar removed / from the path to the added file whose path starts from the root.

Deleting a file from an archive:

BASH
tar --delete -f archive.tar etc/passwd
Click to expand and view more

--delete deletes the file specified at the end from the archive, -f is the archive name. For compressed archives, the situation is similar to adding files: decompress, delete, compress.

Check that the file was deleted from the archive:

BASH
tar -t -f ./archive.tar
Click to expand and view more

Compressing a tar archive

All this is good, but an archive without compression is like a sausage sandwich without cheese😋.

Options without a hyphen🙄

It is important to note that the tar command has special options for compressing an archive using different formats/algorithms. Thanks to this, everything looks transparent to the user. But if the corresponding utility is missing from the system (for example, xz), the tar command will exit with an error.

Compression during archiving

BASH
tar -c -z -f ./archive.tar.gz ./file1 ./file2
Click to expand and view more

-z means use gzip.

Note that the generally accepted extension for compressed gzip files is .gz. Since tar only creates the archive (tarball), while an external utility compresses it, the double extension .tar.gz is specified. Some people do not like this form very much (including me), so there is another generally accepted extension for such files: .tgz.

For comparison, create a similar archive without compression and find out the archive sizes using the du (disk usage) utility:

BASH
tar -c -f ./archive.tar ./file1 ./file2

du -sh ./archive.t*
Click to expand and view more

But where is the compression? The thing is that we archived and compressed files created with the dd command and a stream of pseudorandom binary data, which may not be compressible at all.

For clarity, create a 50 MB file and fill it with zeros. Then create a regular archive and a compressed one to see the difference in size:

BASH
dd if=/dev/zero of=./file50m bs=5M count=10

tar -c -f ./archive50m.tar file50m

tar -c -z -f ./archive50m.tgz file50m

du -sh ./archive50m.t*
Click to expand and view more

The difference is obvious! But that is because the files are filled with zeros, which compress well. The same applies to any text. With this example, I wanted to show you that compression may not be justified in terms of server resource utilization, especially when working with large files.

To clearly see the difference between formats, create a couple of text files:

BASH
yes "The quick brown fox jumps over the lazy dog" | head -n 1000000 > ./file1.txt

yes "Eat some more of these soft French buns and have some tea" | head -n 1000000 > ./file2.txt
Click to expand and view more

Create a tar archive and compress it with gzip:

BASH
tar -c -z -f ./archive.tar.gz ./file1.txt ./file2.txt
Click to expand and view more

And other formats:

BASH
tar -c -j -f archive.tar.bz2 ./file1.txt ./file2.txt
Click to expand and view more

-j means compress with bzip2.

BASH
tar -c -J -f archive.tar.xz ./file1.txt ./file2.txt
Click to expand and view more

-J means compress with xz.

BASH
tar -c --zstd -f archive.tar.zst ./file1.txt ./file2.txt
Click to expand and view more

--zstd means compress with zstd.

Let’s look at the result:

BASH
du -sh ./archive.tar.*
Click to expand and view more
BASH
40K     ./archive.tar.bz2
468K    ./archive.tar.gz
24K     ./archive.tar.xz
16K     ./archive.tar.zst
Click to expand and view more

zstd not only compressed better than the others, but also did it lightning-fast, especially compared to bzip2.

Extraction works similarly; tar determines the compression method itself:

BASH
tar -x -f ./archive.tar.gz
tar -x -f ./archive.tar.bz2
tar -x -f ./archive.tar.xz
tar -x -f ./archive.tar.zst
Click to expand and view more

It is also worth noting the ability to explicitly specify the archive compression command for tar using the -I option. Example:

BASH
tar -v -I "zstd -19" -c -f ./archive.tzst ./file1.txt ./dir
Click to expand and view more

Here we also specified the compression level immediately 😏.

Compressing individual files

Sometimes there is no need to create a separate archive, and you only need to compress one file.

The gzip utility

Syntax:

BASH
gzip [options] <file_to_compress>
Click to expand and view more

Examples:

BASH
gzip ./file1.txt
Click to expand and view more

Creates file.txt.gz and deletes the original.

BASH
gunzip ./file1.txt.gz
# or
gzip -d ./file1.txt.gz
Click to expand and view more

-d — decompress.

BASH
gzip -k ./file1.txt
Click to expand and view more

You can specify the compression level: the default level is 6 (a balance between speed and size), and the maximum is 9:

BASH
gzip -9 ./file1.txt
Click to expand and view more

The higher the level, the better the compression, but the slower the speed.

The bzip2 utility

It works like gzip, but usually compresses better, although more slowly.

Syntax:

BASH
bzip2 [options] <file_to_compress>
Click to expand and view more

Examples:

BASH
bzip2 ./file1.txt
Click to expand and view more

Creates file.txt.bz2 and deletes the original.

BASH
bunzip2 ./file1.txt.bz2
# or
bzip2 -d ./file1.txt.bz2
Click to expand and view more
BASH
bzip2 -k ./file1.txt
Click to expand and view more
BASH
bzip2 -9 ./file1.txt
Click to expand and view more

The xz utility

A modern compression algorithm, usually more efficient than gzip and bzip2, but slower 🐌.

Syntax:

BASH
xz [options] <file_to_compress>
Click to expand and view more

Examples:

BASH
xz ./file1.txt
Click to expand and view more

Creates file1.txt.xz and deletes the original.

BASH
unxz ./file1.txt.xz
# or
xz -d ./file1.txt.xz
Click to expand and view more
BASH
xz -k ./file1.txt
Click to expand and view more
BASH
xz -9 ./file1.txt
Click to expand and view more

The zstd utility

zstd is a modern compression algorithm from one banned organization🙈.
It is faster than gzip / bzip2 / xz while providing excellent compression👍. It is suitable for both archives and streaming compression (for example, in systemd, tar, rsync).

Syntax:

BASH
zstd [options] [file_to_compress]
Click to expand and view more

Examples:

BASH
zstd ./file1.txt
Click to expand and view more

Creates file1.txt.zst and deletes the original.

BASH
zstd -k ./file1.txt
Click to expand and view more
BASH
unzstd ./file1.txt.zst
# or
zstd -d ./file1.txt.zst
Click to expand and view more
BASH
zstd -19 ./file1.txt
Click to expand and view more

Archiving and compressing data streams

If you do not know or poorly understand what this is, I highly recommend my introductory article on this topic:
🔗 Linux command line, input and output redirection: “>”, “<“, “|” operators

P.S. I did not find a meme about stdin/stdout, so a neural network generated the image. A bit over the top, but it made me laugh😂😂

Creating an archive (basic operations)

BASH
tar -c -f - ./file1 ./file2 ./dir/ > ./archive.tar
Click to expand and view more
BASH
tar -c -z -f - ./file1 ./file2 ./dir/ > ./archive.tgz
Click to expand and view more
BASH
tar -c -f - ./file1 ./file2 ./dir/ | gzip -9 > ./archive.tgz
Click to expand and view more
BASH
find ./ -name 'file[1-2]' | tar -c -z -f ./archive.tgz -T -
Click to expand and view more

find in the command above searches for all files named file1 and file2 in the current directory and its subdirectories.

Working with a remote server (🔗 SSH)

BASH
tar -c -z -f - ./dir/ | ssh ivan@test.r4ven.me "tar -C /tmp -x -z -f -"
Click to expand and view more
BASH
ssh ivan@test.r4ven.me "tar -c -z -f - ./file1 ./file2" > ./archive.tgz
Click to expand and view more
BASH
ssh ivan@test.r4ven.me "cat ./archive.tgz" | tar -C /tmp -x -z -f -
Click to expand and view more

Encryption

BASH
tar -c -z -f - ./file1 ./file2 ./dir/ | gpg --batch --symmetric --passphrase "MyPassword" > ./archive.tgz.gpg
Click to expand and view more
BASH
gpg -d ./archive.tgz.gpg | tar -x -z -f -
Click to expand and view more

Splitting into parts

BASH
tar -c -z -f - ./dir/ | split -b 200K - ./archive.tgz.part-
Click to expand and view more
BASH
cat ./archive.tgz.part-* | tar -x -z -f -
Click to expand and view more

Alternative archivers: zip, 7z, rar

The zip archiver

zip is a universal archiver (it both compresses and archives), popular in Windows.

Syntax:

BASH
zip [options] <archive_name> <files_or_directories>
Click to expand and view more

Examples:

BASH
zip ./archive.zip ./file1 ./dir/
Click to expand and view more
BASH
unzip ./archive.zip
Click to expand and view more
BASH
unzip -l ./archive.zip
Click to expand and view more

-l = list (show the list of files).

BASH
zip ./archive.zip ./file2
Click to expand and view more
BASH
zip -0 ./archive.zip ./file1.txt # no compression (packing only)

zip -9 ./archive.zip ./file1.txt # maximum compression
Click to expand and view more

The 7z archiver (7-Zip)

An archiver with an excellent compression ratio. Utilities: 7z or 7za (from the p7zip package).

Syntax:

BASH
7z <operation> <archive_name> <files_or_directories>
Click to expand and view more

Examples:

BASH
7z a ./archive.7z ./file1 ./dir/
Click to expand and view more

a = add (add to the archive).

BASH
7z x ./archive.7z
Click to expand and view more

x = extract while preserving the directory structure.

BASH
7z l ./archive.7z
Click to expand and view more

l = list (show the list of files).

BASH
7z a ./archive.7z ./file2
Click to expand and view more

a = add.

BASH
7z a -mx=0 archive.7z ./file1.txt # no compression

7z a -mx=9 archive.7z ./file1.txt # maximum compression
Click to expand and view more

The rar archiver

Another popular archiver. It is known for bringing its developer a fabulous amount of… money verbal gratitude👏. The eponymous proprietary rar utility is used. unrar (open source) is usually used for extraction.

Syntax:

BASH
rar <operation> <archive_name> <files_or_directories>
Click to expand and view more

Examples:💡 a = add.

BASH
rar a ./archive.rar ./file1 ./dir/
Click to expand and view more

a = add.

BASH
unrar x ./archive.rar
Click to expand and view more

x = extract while preserving the directory structure.

BASH
unrar l ./archive.rar
Click to expand and view more

l = list (show the list of files).

BASH
rar a ./archive.rar ./file2
Click to expand and view more

a = add.

The rar utility also allows you to choose the compression level:

BASH
rar a -m0 ./archive.rar file1.txt # no compression

rar a -m5 archive.rar file1.txt   # maximum compression
Click to expand and view more

A simple comparison test

Compress:

BASH
zip -9 ./archive.zip ./file* ./dir

7z a -mx=9 archive.7z ./file* ./dir

rar a -m5 ./archive.rar ./file* ./dir

tar -I "zstd -19" -cvf ./archive.tzst ./file* ./dir
Click to expand and view more

View the size:

BASH
du -s ./archive.*
Click to expand and view more

Result:

BASH
1008  ./archive.7z
2004  ./archive.rar
2008  ./archive.tzst
1128  ./archive.zip
Click to expand and view more

zstd worked faster than all the others, but it did not provide the best compression🤔. Different formats probably work more efficiently for different file sets🤷♂️. It is recommended to determine this experimentally👨💻.

Next time, we will write a backup script in Bash that will archive files on a schedule📋. Do not miss it😉.

Useful materials

Copyright Notice

Author: Ivan Cherniy

Link: https://r4ven.me/en/linux/komandnaya-stroka-linux-arhivirovanie-i-szhatie-komandy-tar-gzip-bzip2-xz-zstd-i-zip-7z-rar/

License: CC BY-NC-SA 4.0

Blog materials may be used with attribution to the author and source, for non-commercial purposes, and under the same license.

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut