Как работать с архиваторами в консоли Linux (шпаргалка)

Часто при работе в консоли linux приходится создавать архивы, или наоборот распаковывать их. Эта статья — шпаргалка основных команд, используемых при работе с основными архиваторами.
Как создать или распаковать архивы tar, tar.gz, tar.bz2 в консоли Linux
Опции tar:
- c — создание нового архива (сокращение от create)
- v — выдача дополнительных сообщений в процессе работы программы
- f — создание файла на диске.
- z — использовать для сжатия GZip
- j — использовать для сжатия BZip2
- x — распаковать архив
Упаковка в архив файлов или папок
Упаковать файл или папку в архив tar
С папкой всё аналогично:
Можно упаковать сразу несколько папок или файлов:
Можно указать пути к папкам, или файлам, а также путь к файлу архива.
Обратите внимание, что в этом случае нужно добавить опцию -C, а далее слэш / с обоих сторон, отделённый пробелами. При этом путь к папке, которую архивируем, уже указываем без слэша в начале.
Без этой опции тоже будет работать, но tar постоянно будет ругаться вот так: tar: Removing leading `/’ from member names
При необходимости, можно исключить файлы или папки из архива. Например вот так, в архив не попадут все файлы из папок folder1 и folder3, при этом сами эти папки в архив попадут пустыми:
А вот так, в архив не попадут и сами папки:
Можно указывать полный путь к папке, которую нужно исключить:
Можно —exclude указывать несколько раз:
Можно исключить файлы или папки по маске:
Упаковать папку в архив и сразу отправить на удалённый сервер по ssh:
Упаковать файл или папку в архив tar.gz
Здесь всё те же команды, что и просто с tar, которые приведены выше, только добавляем в начале опцию z и имя создаваемого архива указываем с расширением .tar.gz:
Упаковать файл или папку в архив tar.bz2
Опять, всё тоже самое, что и в случаях выше, только уже указываем опцию j, и имя создаваемого архива указываем с расширением tar.bz2:
Как посмотреть содержимое архива
Всё просто, используем опцию t. Работает и с простыми архивами tar, и со сжатыми в tar.gz или tar.bz2:
Как распаковать архивы tar, tar.gz, tar.bz2
Распаковать архив tar
Распаковать архив tar в определённую папку:
Распаковать архив tar.gz
Распаковать архив tar.gz в определённую папку:
Распаковать архив tar.bz2
Распаковать архив tar.bz2 в определённую папку:
Как создать или распаковать архивы zip в консоли Linux
Упаковка в архив файлов или папок
Упаковать файл в архив zip
Упаковать папку в архив zip
При архивировании папки нужно добавить опцию -r, иначе в архив не попадут вложенные в папку другие папки и файлы:
Как распаковать архивы zip
Если нужно распаковать архив zip в определённую папку, то нужно добавить опцию -d
Нужна профессиональная удалённая помощь с сервером, сайтом, компьютером или ноутбуком?
Свяжитесь со мной любым удобным для вас способом, и получите её быстро и не дорого.
How to Extract/Unzip .tar.gz Files: Step-by-Step Windows and Linux Guide

The term “tarball” is derived from two components: “.tar” representing the Tape Archive format and “.gz” denoting the gzip compression algorithm.
.tar.gz files are widely used for source code Distribution & Web Server Deployment due to their versatile nature and efficient compression.
First, let’s understand what the difference between .tar & .tar.gz file format and the benefits of it.
Then we’ll jump into the step-by-step process of unzipping on both Linux and Windows platforms.
Let’s get rolling!
.tar Files

The .tar extension stands for “tape archive.”
A .tar file is an archive that does not undergo any compression.
It just bundles files & directories together while preserving their file structure and metadata. This means it takes all the specified files and puts them together into one container.
But it does not compress the data, which results in a larger file size compared to compressed formats.
.tar.gz Files

These files are a combination of two steps: Archiving and Compression.
The .tar.gz extension indicates a file that is a .tar archive and compressed using the gzip utility.
Gzip compression reduces the overall file size, which makes it more efficient for distribution, backup, and storage purposes.
This format is common in the Unix/Linux world and is widely used to create compressed archives.
This compression is lossless – that means no data is lost during the compression process, and the original files can be fully restored upon extraction.
Also read: tar Command Examples for Sysadmin and Developers
.tar vs .tar.gz Files

Both these file archives are used for binding multiple files and directories into a single file, but they just differ in their compression methods. Here are some general differences between the .tar and .tar.gz files.
| Feature | .tar Files | .tar.gz Files |
| Compression | No compression, files are stored as it is. | Compressed using gzip |
| File Extension | .tar | .tar.gz or .tgz |
| Compression Ratio | None | High compression ratio |
| Ideal Use | Archiving only | Distribution and Archiving |
| File Size | Larger | Smaller |
| Extraction | Quick | Slower (due to decompression) |
| Use Case | Archiving files, creating backups | Efficient data transfer, software distribution |
Benefits of .tar.gz Files
These files offer several benefits that make them a popular choice for archiving and distributing files. Here are some of the key advantages:
Preservation of File Attributes
.tar.gz files retain important file attributes such as permissions, timestamps, and ownership information. When the archive is extracted, these attributes are restored. That means they maintain their original characteristics.
File Organization
As already discussed, The .tar format allows bundling multiple files into a single file which makes it easier to organize related data or complex directory structures into a single archive.
This simplifies file management and reduces the risk of data loss during transfers.
Checksum Integrity
gzip compression uses a checksum to make sure data integrity. When you extract files from a .tar.gz archive, the checksum is automatically verified to detect & handle any potential data corruption.
Open Source Standard
The .tar.gz format is an open-source standard. That means it is not tied to any specific proprietary software.
Incremental Backups
These files can be used in incremental backup strategies – where only new or modified files are added to the archive.
Extracting .tar.gz Files for Linux
To unzip the .tar.gz files, you’ll need to use specific commands and tools depending on your operating system. Let’s explore the extraction process for both Linux & Windows platforms.
Linux systems come with built-in tools that can extract .tar.gz files easily. The most commonly used command-line tool for this purpose is tar. Follow these steps:
Method 1: Using the Command Line
Step 1: Open a terminal.
Step 2: Navigate to the directory where your file is located using the ‘cd” command. For example, To navigate to the “Downloads” folder:
Step 3: And the next step is to unzip the .tar.gz archive format. For that, just use the following command
The options used here are:
z: Use gzip to decompress the file.
x: Extract the files.
v: Verbose mode (optional but provides detailed output).
f: Specify the filename to be extracted.

You can notice in the above image that the archive files are extracted in the same working directory.
Method 2: Using File Manager (GUI)
Step 1: Open the file manager (e.g., Nemo, Nautilus, Dolphin).
Step 2: Right-click the .tar.gz file.
Step 3: Select the “Extract Here” or “Extract to” option – depending on whether you want the files to be extracted in the same location or a different folder.

The files will be extracted to the selected location.
Extracting .tar.gz Files for Windows
You can easily extract .tar.gz files using third-party tools like 7 zip and Winrar on the Windows system.
Method 1: Using 7-Zip
7-Zip is a free and open-source tool with high compression ratios & supports a wide range of archive formats. It offers AES-256 encryption to protect sensitive data within archives. Users can utilize the 7-zip command-line interface for automated & scripted extraction tasks.
It also integrates with the Windows Explorer context menu, which enables users to create and extract archives directly from the right-click menu.

Step 1: Visit the official website & download the suitable version for your Windows OS.
Step 2: Install 7-Zip by following the on-screen instructions.
Step 3: Navigate to the directory and right-click on the file you want to extract.
Step 4: Hover over the 7-Zip option, and choose “Extract Here” from the context menu.

The extraction method is precisely the same for tar files that have compression, such as.tar.gz,.tar.bz2, and others.
Method 2: Using WinRAR
WinRAR is a popular file compression & archive utility software. It allows users to create, view, and extract files in various archive formats, including its native .RAR format as well as other common formats like .ZIP, .7z, ISO, .TAR, and more.
Step 1: WinRAR comes pre-installed on almost every Windows system. In case it’s missing, download and install from the official website.

Step 2: Right-click on the file and then select “Extract Here” to extract the contents of the archive into the same directory or you can also choose the desired location.

WinRAR is distributed as shareware. That means users can download and use it for free during a trial period. Also, its trial version does not have time limitations, and users can still use it even after the trial period has expired, with occasional reminders to purchase the license.
Author’s note✍️
.tar.gz files offer an organized way to store & distribute multiple files while saving disk space.
Whether you prefer command-line tools or graphical file archivers, the extraction process is pretty simple.
In Linux, users have multiple ways to extract .tar.gz files – through the terminal and graphical file archivers. The terminal method is only recommended for those comfortable with command-line interactions, while graphical file archivers provide a user-friendly experience and are good for beginners.
On the other hand, Windows users can rely on third-party file archiver tools like 7-zip or WinRAR to effortlessly extract files.
You may also be interested in learning about the best WinZip alternatives to compress files.
Как распаковать tar bz2 xz gz архивы в Linux

Для распаковки tar-архивов через командную строку используется утилита tar.
Полезно знать, что архивы в формате tar имеют расширение файлов .tar . Также в Linux распространены архивы, которые имеют дополнительное сжатие другими программами. Например, архивы .tar.bz2 , .tar.gz и другие. Все эти архивы можно распаковать утилитой tar.
Распаковка tar
Для распаковки архива в формате .tar в текущую директорию выполните команду:
Распаковка tar.bz2, tar.bzip2, tbz2, tb2, tbz
Распаковка tar.xz, txz
Распаковка tar.gz, tgz
Распаковка tar.lzma
Пояснение опций
x — распаковать архив.
v — Verbose-режим (вывод на экран дополнительной информации во время распаковки).
f — выполнить распаковку архива из файла.
j — вызвать bzip2 для распаковки архива.
z — вызвать gzip
J — вызвать xz
Распаковка в определенную директорию
Чтобы распаковать архив в определенную директорию используется опция -C или —directory , например:
Примечание: директория должна существовать.
Заключение
Мы рассмотрели базовый набор команд, который можно использовать для распаковки различных видов tar-архивов. Существуют также еще некоторые типы архивов, но они менее распространены.
How to Use the Tar Command in Linux
Tar is one of the most widely used Linux commands for compression. There are great benefits in using tar, which is why it’s loved by the pros. Here’s all you need to get started.
Tar stands for Tape Archive and is used to compress a collection of files and folders.

What Is Tar Command Used For
In most cases, once the compression is done using tar, it results in a .tar file. Further compression is done using gzip, which would result in a .tar.gz file.
With tar, you can compress and decompress files. Tar comes with multiple options though there are a few which you may need to remember.
The advantages of tar:
- Tar, when it comes to compression, has a compression ratio of 50%, which means it compresses efficiently
- Drastically reduces the size of packaged files and folders
- Tar does not alter the features of files and directories. The permissions and other features remain intact while compressing
- Tar is widely available across most common Linux versions. This is available on Android firmware as well as supported older Linux flavors.
- Compresses and Decompresses fast
- Easy to use
While this helps us understand tar’s benefits, one question to answer is under what scenario would you choose to use it?
- If you are working on Linux based systems and require file compression
- To transfer a huge collection of files and folders from one server to another
- Take a backup of your website, data or anything else
- To reduce the usage of space on your system, since compression will occupy less space
- To upload and download folders
How to Use Tar in Linux
Let’s learn what basic operations you can perform by using tar. Before we start, you’ll need to SSH into your VPS. Here’s a guide to help you!
Creating a .tar Archive File in Linux
You can create .tar compressions for a file as well as directories. An example of such an archive is:
Here /home/sampleArchive is the directory which needs to be compressed, creating sampleArchive.tar.
The command uses -cvf options which stand for:
- c – This creates a new .tar file
- v – shows a verbose description of the compression progress
- f – file name
Creating a .tar.gz File in Linux
If you want better compression, then you can also use .tar.gz. An example of this is:
The additional option z represents gzip compression. Alternatively, you can create a .tgz file which is similar to tar.gz. An example of this is shown below:
Creating a .tar.bz2 File in Linux
The .bz2 file provides more compression compared to gzip. However, this would take more time to compress and decompress. To create this, you need to use the -j option. An example of the operation is:
This is similar to .tar.tbz or .tar.tb2. An example of this is shown below:
How to Unzip .tar Files in Linux
The tar command can also be used to extract a file. The below command will extract files in the current directory:
If you want to extract to a different directory, then you can use the -C option. One example is shown below:
A similar command can be used to uncompress .tar.gz files as shown below:
.tar.bz2 or .tar.tbz or .tar.tb2 files can be uncompressed similarly. It would require the following command in the command line:
How to List the Contents of an Archive in Linux
Once the archive is built, you can list the contents by using a command similar to the one below:
This will display the complete list of files along with timestamps and permissions. Similarly, for .tar.gz, you can use a command like:
This would also work for .tar.bz2 files, as shown below:
How to Unzip a Single .tar File
Once an archive is created, you can extract a single file. One such example is shown below:
Here example.sh is a single file which will be extracted from sampleArchive.tar. Alternatively, you can also use the following command:
To extract a single file from .tar.gz you can use a command similar to the one shown below:
To extract a single file from .tar.bz2, you can use a command like this:
Or alternatively, one like this:
As you can see, the tar command has a lot of flexibility in its syntax.
How to Extract Multiple Files from .tar Archives
In case you want to extract multiple files, use the below format of the command:
For .tar.gz you can use:
For .tar.bz2 you can use:
Extract multiple files with a pattern
If you want to extract specific patterns of files like only .jpg from the archive, use wildcards. A sample of such command is shown below:
For .tar.gz you can use:
For .tar.bz2 you can use:
How to Add Files to a .tar Archive
While you can extract specific files, you can also add files to an existing archive. To do this, we would use the -r option, which stands for append. Tar can add both files and directories.
Below is an example where we are adding example.jpg into the existing sampleArchive.tar.
We can also add a directory. In the example below, the image_dir directory is added into sampleArchive.tar
You cannot add files or folders to .tar.gz or .tar.bz2 files.
How to Verify a .tar Archive in Linux
Using tar, you can verify an archive. This is one of the ways you can do it:
This cannot be applied to .tar.gz or .tar.bz2 files.
How to Check Archive Size in Linux
Once you create an archive, you can check its size of it. This will be displayed in KB (Kilobytes).
Below are examples of such commands with different archive files:
Conclusion
As you can see, tar is a truly powerful tool that every Linux enthusiast should know. You can further explore the manual pages for the tar command by executing the man tar command. We hope this article helped up your Linux game!
Learn More Linux Commands for File Management
Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.