Как распаковать (разархивировать) файл Tar Gz
Если вы путешествуете по миру открытого исходного кода, скорее всего, вы регулярно сталкиваетесь с файлами .tar.gz . Пакеты с открытым исходным кодом обычно доступны для загрузки в форматах .tar.gz и .zip.
Команда tar используется для создания архивов tar путем преобразования группы файлов в архив. Он поддерживает широкий спектр программ сжатия, таких как gzip, bzip2, lzip, lzma, lzop, xz и compress. Изначально Tar был разработан для создания архивов для хранения файлов на магнитной ленте, поэтому он получил название « T ape AR chive».
Gzip — самый популярный алгоритм сжатия файлов tar. По соглашению имя tar-архива, сжатого с помощью gzip, должно заканчиваться на .tar.gz или .tgz .
Короче говоря, файл с расширением .tar.gz представляет собой архив .tar, сжатый с помощью gzip.
tar можно также использовать для извлечения архивов tar, отображения списка файлов, включенных в архив, добавления дополнительных файлов к существующему архиву, а также для различных других операций.
В этом руководстве мы покажем вам, как распаковать (или распаковать) архивы tar.gz и tgz .
Извлечение файла tar.gz
В большинстве дистрибутивов Linux и macOS по умолчанию предустановлена команда tar .
Чтобы извлечь файл tar.gz, используйте параметр —extract ( -x ) и укажите имя файла архива после параметра f :
Команда tar автоматически определит тип сжатия и распакует архив. Эту же команду можно использовать для извлечения архивов tar, сжатых с помощью других алгоритмов, таких как .tar.bz2 .
Если вы пользователь рабочего стола и командная строка вам не подходит, вы можете использовать файловый менеджер. Чтобы распаковать (разархивировать) файл tar.gz, просто щелкните правой кнопкой мыши файл, который вы хотите извлечь, и выберите «Извлечь». Пользователям Windows потребуется инструмент под названием 7zip для извлечения файлов tar.gz.
Параметр -v сделает команду tar более видимой и напечатает имена файлов, извлекаемых на терминале.
По умолчанию tar извлекает содержимое архива в текущий рабочий каталог . Используйте —directory ( -C ) для извлечения архивных файлов в определенный каталог:
Например, чтобы извлечь содержимое архива в /home/linuxize/files , вы можете использовать:
Извлечение определенных файлов из файла tar.gz
Чтобы извлечь определенный файл (ы) из файла tar.gz, добавьте разделенный пробелами список имен файлов, которые нужно извлечь, после имени архива:
При извлечении файлов вы должны —list их точные имена, включая путь, как напечатано с помощью —list ( -t ).
Извлечение одного или нескольких каталогов из архива аналогично извлечению файлов:
Если вы попытаетесь извлечь несуществующий файл, отобразится сообщение об ошибке, подобное следующему:
Вы также можете извлекать файлы из файла tar.gz на основе шаблона с подстановочными знаками, используя параметр —wildcards и цитируя шаблон, чтобы оболочка не интерпретировала его.
Например, чтобы извлечь файлы, имена которых заканчиваются на .js (файлы Javascript), вы должны использовать:
Извлечение файла tar.gz из stdin
Если вы распаковываете сжатый файл tar.gz, читая архив со стандартного ввода (обычно через канал), вам необходимо указать параметр распаковки. Параметр, который указывает tar читать архивы через gzip, — это -z .
В следующем примере мы загружаем исходники Blender с помощью команды wget и передаем его вывод в команду tar :
Если вы не укажете вариант декомпрессии, tar укажет, какой вариант вам следует использовать:
Вывод файла tar.gz
Чтобы —list список содержимого файла tar.gz, используйте параметр —list ( -t ):
Результат будет выглядеть примерно так:
Если вы добавите параметр —verbose ( -v ), 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.
Распаковка архивов формата TAR.GZ в Linux
Стандартным типом данных файловых систем в ОС Linux считается TAR.GZ — обычный архив, сжатый с помощью утилиты Gzip. В таких директориях часто распространяются различные программы и списки папок, объектов, что позволяет совершать удобное перемещение между устройствами. Распаковывается такой тип файлов тоже достаточно просто, для этого нужно воспользоваться стандартной встроенной утилитой «Терминала». Об этом и пойдет речь в нашей сегодняшней статье.
Распаковываем архивы формата TAR.GZ в Linux
В самой процедуре распаковки нет ничего сложного, пользователю потребуется только узнать одну команду и несколько связанных с ней аргументов. Инсталляция дополнительных инструментов при этом не требуется. Процесс выполнения поставленной задачи во всех дистрибутивах одинаков, мы же взяли за пример последнюю версию Ubuntu и предлагаем вам пошагово разобраться с интересующим вопросом.
- Для начала необходимо определить место хранения нужного архива, чтобы в дальнейшем перейти в родительскую папку через консоль и уже там осуществлять все остальные действия. Поэтому откройте файловый менеджер, найдите архив, щелкните по нему правой кнопкой мыши и выберите «Свойства».
- Откроется окно, в котором можно получить детальную информацию об архиве. Здесь в разделе «Основные» обратите внимание на «Родительская папка». Запомните текущий путь и смело закрывайте «Свойства».
Как вы могли заметить, при вводе каждой стандартной команды tar мы использовали одновременно несколько аргументов. Вам нужно знать значение каждого из них хотя бы потому, что это поможет лучше понимать алгоритм распаковки в последовательность действий утилиты. Запомнить потребуется такие аргументы:
How To Extract and Unzip .tar.gz Files (for Linux and Windows)
From videos to entire software packages, many files are compressed and stored using the .tar.gz format. While extracting a .tar.gz file isn’t quite as easy as unzipping a .zip, it’s still pretty straightforward.
As software becomes more powerful and media becomes more data-rich, file sizes continue to grow at exponential rates. As a result, it’s becoming increasingly common to store and send files in compressed formats as .tar.gz.
Compressing and extracting these files, however, isn’t always intuitive. In this guide, we’ll provide basic guides to unzip .tar.gz files in Linux and Windows, as well as a few helpful tips and tricks.
What Are .tar and .tar.gz Files?
A “.tar” file is a collection of files compressed into a single file or archive. Short for “Tape ARchive,” the name “TAR” is a throwback to when files were stored on magnetic tape drives.
Thankfully, you don’t need to be a 1960s computer technician to use and extract .tar files – nor do modern .tar files even have anything to do with old computers.
Just like the more familiar .zip files, .tar files compress large files into a single package, making it easier to store and send them through email, servers, and so on. As a result, it’s become a common file extension for many open-source software packages and other resources.
Try Kinsta Risk-Free
Optimize your admin tasks and budget with $275+ enterprise-level features included free in all WordPress plans. Backed by a 30-day money-back guarantee.
But with .zip being the easier of the two to use, why use .tar in the first place? As we’ll see in the next section, .tar comes with a few extra features that make it the better compression format for certain files and applications.
.tar vs .zip
Where most operating systems make it easy to extract and create .zip files, the same can’t really be said for .tar files — at least not in ways that are easy to notice.
Of course, that’s not to say .tar files are some kind of “lesser” format than .zip. Rather, they both accomplish the same task (file compression) in the same way. Here’s a breakdown of how it all works.
- A .tar file is a collection of uncompressed files, sometimes known as a tarball. Since .tar doesn’t compress anything, it requires a separate compression utility for compression. As we’ll see later, one popular compression utility is gzip, which compresses a .tar into a .tar.gz file.
- A .zip file is a collection of compressed files. Rather than use a separate compression utility to compress the entire collection, .zip automatically compresses each file within the collection.
By now, you’ve probably noticed the major difference between .tar and .zip files: compression methods.
Where .zip files consist of many individually compressed files, .tar files are compressed as a single package, leaving its files uncompressed. In other words, .zip files are a collection of compressed files, while .tar files are a compressed collection of files.
But does the compression method really matter, especially if both methods technically produce compressed files?
It depends. For sending and storing, both .zip and .tar.gz files will allow you to send relatively large packages as a single file. However, there are some pretty major differences when it comes to accessing data within the files and the compression efficiency.
- .zip files are more accessible. Since data in a .zip are compressed individually, they can also be accessed individually. By contrast, data in a .tar.gz is only accessible after extracting the entire file.
- .tar.gz files are more space-efficient. Since .tar files are compressed as a single entity rather than a group of individually compressed files, compression utilities can group similarities between files and cut down on space. In other words, compressing files as a single group allows for more efficient compression methods, thereby saving space and reducing the overall size of the file.
If that’s not entirely clear, don’t worry. Technical details aside, all you need to remember is that .zip files are more accessible but less space-efficient, while .tar files are less accessible but more space-efficient. As a result, one isn’t necessarily better than the other — it’s all a matter of application.
What’s The Difference Between .tar and .tar.gz Files?
While both .tar and .tar.gz refer to file archives, a .tar.gz file is a .tar file that’s been compressed or “zipped” using the gzip utility. Using gzip for compression is what gives the file a “.gz” double extension.
Though gzip is the most common compression utility, it’s not the only one. As you might imagine, using a different compression utility on a .tar file will result in a different double extension. Some common examples include .tar.bz2 (bzip2), .tar.br (Brotli), and .tar.zst (zstd), among many others.
As we’ll see later, different compression utilities may require different methods for extracting and unzipping files. Though we’ll mostly focus on .tar.gz files, check out the end of the article for some quick tips on extracting .tar files in other formats.
Otherwise, keep reading to learn how to unzip .tar.gz files in Linux, macOS, and Windows.
How Do I Unzip a .tar.gz File in Linux Terminal?
Most Linux distributions and macOS include built-in tools for zipping and unzipping .tar and .tar.gz files. While the tar utility is enough for most purposes, you’ll need the gzip utility to create .tar.gz files.
Unzip .tar.gz in Linux
You can unzip most .tar.gz and other compressed .tar files using the tar utility.
For the simplest method, begin by opening the terminal (CTRL+ALT+T) and navigate to the directory of the .tar.gz file you want to unzip. Then enter the following command:
Extract .tar.gz file to current working directory:
This command will extract ( -x ) the file ( -f ) specified (in this case, filename.tar.gz) to the current directory. Note that this command also works with other common compression formats such as .tar.bz2.
The tar command also comes with several other options. Like many Linux commands, one of these is a verbose output ( -v ) that prints the extracted files to the terminal window:
Extract .tar.gz file to current working directory and print output:
Again, the above commands will extract to the current working directory by default. You can use the -C option to extract to a different directory (in this case, /home/user/files).
Extract .tar.gz file to a different working directory:
Only Extract Specific Files or Directories From .tar.gz in Linux
The tar command also provides support for extracting only specific files or directories from a .tar.gz file. Simply add a space-separated list of the files you want to extract.
Extract file1 and directory1 from .tar.gz file to current working directory:
Note that this command will throw an error unless you specify the exact filename listed in the .tar file. As we’ll cover more in the next section, you can verify file names by listing contents with the tar -tf filename.tar.gz command.
You can also use —wildcards to extract all files with a certain extension or name.
Extract all files ending with “.txt” from .tar.gz file:
Unzip .tar.gz From stdin in Linux
You can also extract .tar.gz directly from the standard input stream (stdin) by piping it into the tar command using the decompression option ( -z ).
For example, if you wanted to extract the .tar.gz file located at “https://kinsta.com/filename.tar.gz” (there’s not actually a .tar.gz file here, but bear with us), you’d use the wget command piped into tar .
Extract .tar.gz file from a URL:
List Contents of .tar.gz File in Linux
It’s often useful to list the contents of a .tar.gz file without having to unzip the entire archive. The -list ( -t ) option will output a list of filenames.
List contents of a .tar.gz file:
You can also add the verbose output option ( -v ) to provide detailed listings, including dates, securities/permissions, and more.
List detailed contents of a .tar.gz file:
Many compression utilities also offer their own commands for listing the contents of compressed files. For example, gzip allows you to list the contents of a .gz file with the following command:
List detailed contents of a .gz file with gzip:
Zip and Unzip .tar and .tar.gz in Linux with gzip
You can create your own compressed .tar files using compression utilities such as gzip . Gzip is one of the most popular and available options, especially since it comes built in to most Linux distributions and macOS.
In the terminal, navigate to the working directory of the .tar file you want to compress and simply enter the following command:
Compress .tar file with gzip:
You can just as easily unzip the resulting .tar.gz file with the decompress ( -d ) option.
Decompress .tar.gz file with gzip:
If you want to keep the original file after compression, there are two options. The first is the -k option, and the other uses the -c option to output the compressed file to a different file, preserving the original.
Compress .tar file and keep original copy:
Compress .tar file and store as a different file:
Like the tar utility, gzip also allows you to zip and unzip multiple files or entire directories at a time.
Compress multiple files:
Decompress multiple files:
Compress all files in a directory:
Decompress all files in a directory:
How Do I Unzip a .tar.gz File in Windows 10?
Like Linux and macOS, the Windows 10 operating system also includes a built-in tar utility.
Unlike Windows’ convenient graphical user interface (GUI) for unzipping .zip files, you’ll need to use the tar utility through the command line. However, there are also many third-party tools you can install for a more user-friendly experience.
Using the Command Line (cmd)
To access the Windows command line, search for “command prompt” or “cmd” in the search bar. Right-click the first result and select the “Run as administrator” option.
The Command Prompt icon after searching “cmd” in Windows 10/11
With the command prompt open, use the appropriate commands to change the current working directory ( cd ) to the location of the .tar.gz file you want to unzip. Alternatively, you can also specify a source and destination file path when using the tar utility.
Type one of the following commands and press “Enter.”
Extract .tar.gz file to current working directory:
Extract .tar.gz file from source path to destination path:
Note that the tar utility in Windows has nearly the same syntax as it does in Linux and macOS. Here we’ve used the extract ( -x ), verbose ( -v ), decompress with gzip ( -z ), and file ( -f ) options for a complete extraction with decompression and detailed output.
Using Third-Party Tools
If the command line isn’t your thing, there are plenty of user-friendly tools available to unzip tar.gz files.
Compressing a large number of files into a .zip using 7-Zip
While there are many tools to choose from, the most popular include 7-Zip and WinZip. While slightly different, they are quite lightweight and offer a much simpler alternative to using the command line.
Some third-party tools also offer extended flexibility for converting between file types, saving more time if you want to change between compression formats. Many are also available for Linux and macOS.
Compatibility options in 7-Zip including .tar and .gz.
However, while tools like 7-Zip are free, many more “robust” solutions are only available for a price after a trial period. As a result, we recommend sticking to free (but trustworthy) tools or simply using the command line.
Troubleshooting Common Errors
Not every .tar.gz extraction is seamless — especially if you’re using the command line!
Where commands have little (if any) room for typos or omissions, many common errors are the result of small mistakes, misspellings, or incorrect formats. Thankfully, unless you’re somehow missing your tar or gzip utility, most common errors are very easy to fix.
tar: README: Not found in archive
This error occurs when trying to extract specific files or directories from a .tar.gz file using tar .
Error Input:
Error Output:
In this example, the user tried to extract the file titled “FILE” from filename.tar.gz. However, tar was unable to find FILE within .tar.gz, meaning that the user either misspelled the name or that the file simply doesn’t exist in filename.tar.gz. Another common cause of errors is case sensitivity, where Linux treats “FILE” and “file” as two separate entities.
Solution: Check the spelling and/or verify that the file exists in the .tar.gz archive by listing the contents with tar -tf filename.tar.gz .
tar: Archive is compressed. Use -z option
This error occurs if you try to decompress a file without specifying a decompression utility, specifically -z for gzip .
Error Input:
Notice that the “ -z ” is missing from what should be sudo tar -xz on the far right.
Error Output:
Solution: Specify a decompression option such as gzip ( -z ) in the tar command.
gzip: stdin: not in gzip format
Many users report running the “right” commands only to find that their .tar.gz is “not in gzip format” – despite the .gz extension.
Error Output:
This error usually occurs when a .tar has been saved as a .gz despite having never been compressed using the gzip utility. It may sound like a silly mistake, but it’s surprisingly common in situations where users directly rename files and their extensions (such as .tar and .gz) in the process.
Solution: Find a new copy of the .tar.gz file, or simply extract it as a .tar file using tar -xf filename.tar instead. If this command also throws an error, the next solution might help.
tar: Unrecognized archive format
Similar to the previous error, this error occurs when an archive was saved as a .tar despite not being a .tar archive.
Error Output:
Solution: Find a new copy of the .tar or .tar.gz file, or try extracting with gunzip filename.tar.gz instead. If the gunzip command doesn’t work, try listing the contents with verbose output with tar -xvf filename.tar.gz and see if there’s a specific file causing the problem. However, it’s more likely that the file was never properly zipped as a .tar file in the first place.
It’s easy to get confused when navigating between .tar, .tar.gz, and .gz – not to mention zipping and unzipping them. Here are a few frequently asked questions we commonly hear from users working with .tar.gz files.
How Do I Open A .tar.gz File?
You can open most .tar.gz files using the tar command built in to Linux, macOS, and Windows 10. If you’re not comfortable with the terminal or command line, third-party tools such as 7-Zip offer a more user-friendly alternative.
Is .gz a .tar File?
While every tar.gz file is a .tar archive, not every .gz is a .tar file. The .gz extension represents the gzip compression format, which can be applied to almost any file format to compress data and save space.
Is .tar.gz The Same As .zip?
Though both .zip and .tar.gz archive and compress files, they do so in different ways. Where .zip archives and compresses individual files, .tar only archives individual files, leaving a separate compression format such as .gz (gzip) to compress all of them as a single file/archive. In other words, .zip is a collection of compressed files, while .tar.gz is a compressed collection of files.
Is .tar.gz More Efficient Than .zip?
Yes. Since .tar.gz compresses multiple files all at once, it can take advantage of similarities between individual files to save on space. Generally speaking, a collection of files archived and compressed as a .tar.gz will be more space-efficient (i.e., smaller) than the same collection compressed as a .zip.
Summary
With Linux, macOS, and Windows 10 offering a built-in tar utility, it’s easier than ever to unzip tar.gz files through the command line. Usually, the only command you’ll really need is:
Like many archive and compression formats, .tar.gz is an effective way to save storage space and make it easier to send large amounts of data. If you plan to distribute and store .tar.gz files on your website, Kinsta’s managed hosting services can help make the most of your space.
For more information and to schedule a live demo, contact a hosting expert from Kinsta today.
Get all your applications, databases, and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Get started with a free trial of our Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.