Данная статья представляет собой краткое руководство по использованию GnuPG (он же GPG). В ней вы найдете основные команды, примеры использования, а также инструкции по прикручиванию GPG к почтовым клиентам. Далее предполагается, что вы знакомы с принципом работы GPG и объяснять, например, что такое ассиметричная криптография, открытый и закрытый ключ, цифровая подпись и так далее, не требуется. За несколько десятилетий существования GPG никто особо не преуспел в его взломе, что как бы намекает нам, что это довольно надежное решение как для обмена зашифрованными сообщениями, так и просто шифрования файлов.
Терминология
Существует некоторая путаница в терминологии. Например, далеко не все могут внятно объяснить, чем PGP отличается от GPG. Давайте же во всем разберемся.
- OpenPGP — стандарт шифрования, описанный в RFC 4880 и RFC 6637. Не следует путать с конкретными реализациями, такими, как PGP и GPG;
- GnuPG или GPG — конкретная открытая (GPLv3) реализация OpenPGP, речь о которой пойдет в настоящей статье;
- PGP — сильно проприетарная реализация OpenPGP от компании PGP Corporation. В 2010-м году компанию купила Symantec, а ее продукты переименовала во что-то типа Symantec Desktop Email Encryption;
Часто, говоря «PGP», люди имеют в виду способ шифрования, описанный в OpenPGP, и соответственно любую из его реализаций.
Основные команды GnuPG
Хорошей идеей будет выбрать алгоритм RSA и длину ключей 4096 бит.
Важно! Не забудьте пароль от закрытого ключа.
Частая проблема — сообщение вроде такого:
Not enough random bytes available. Please do some other work to give
the OS a chance to collect more entropy! (Need 204 more bytes)
Решается она установкой демона для сбора энтропии:
Просмотр списка ключей:
gpg
gpg
gpg
Получение fingerprint ключа:
Fingerprints используются в основном для проверки того, что с сервера ключей (см далее) был импортирован действительно правильный ключ. Для поиска их не используют.
Для отображения более безопасных длинных id используйте опцию keyid-format:
gpg LONG
gpg 0xLONG 7EFE74E5
Короткие keyid удобны для манипуляции с ключами локально. Для поиска всегда следует использовать длинные id и проверять fingerprints. В последних версиях GPG длинные id используются по умолчанию.
gpg 8640D6B9
gpg 8640D6B9
Экспорт открытого ключа в текстовом виде (можно писать на всех заборах):
gpg pubkey.txt 8640D6B9
Экспорт закрытого ключа в текстовом виде (ключ все еще зашифрован мастер-паролем, можно использовать для бэкапа в Git):
gpg privkey.txt 8640D6B9
Импорт открытого ключа:
Импорт закрытого ключа:
Если не указать , импортируется только открытый ключ, и при попытке подписать что-то вы будете получать странные ошибки вроде:
gpg: no default secret key: secret key not available
gpg: msg.txt: sign+encrypt failed: secret key not available
Экспорт открытого ключа на keyserver:
gpg pgp.mit.edu 8640D6B9
Важно! После того, как вы залили ключ на keyserver, его будет невозможно удалить, только сделать revoke. Убедитесь, что вы сделали надежную резервную копию ключа. Если вы раньше никогда не работали с PGP/GPG, очень советую сначала потренироваться на почтовых адресах в зоне example.ru.
Hint: чтобы постоянно не указывать , просто допишите в ~/.bashrc:
=”gpg –keyserver pgp.mit.edu”
Импорт открытого ключа с keyserver:
В мире PGP/GPG существуют так называемая сеть доверия (web of trust). В двух словах это означает, что GPG не доверяет ключу, если только он не подписан кому вы доверяете. Кроме того, если вы доверяете Пете, а Петя доверяет Коле, то вы автоматически доверяете Коле. В частности, по умолчанию при проверке подписи и прочих действиях GPG будет ругаться так:
WARNING: This key is not certified with a trusted signature!
There is no indication that the signature belongs to
the owner.
Чтобы исправить это, говорим:
Затем в диалоге говорим , жмем 5 («I trust ultimately»), говорим . Другие ключи можно подписать командой . Кстати, там же можно сменить пароль от вашего ключа (команда ), изменить дату экспирации ключа в любую сторону (команда ), добавить имя/email (команда ), удалить имя/email (команда ), посмотреть алгоритмы шифрования, используемые по умолчанию () и делать другие интересные вещи.
Примечание: Что делать, когда ключ заэкспайрился? В этом случае можно изменить дату экспирации на более позднюю и перезалить ключ. Или же создать новый ключ, подписать его старым, и залить новый ключ на keyserver. Делать revoke не требуется.
Вы можете подписать чей угодно ключ и залить подписанный ключ на сервер, подтвердив тем самым, что ключ действительно принадлежит человеку, указанному в описании:
gpg 7EFE74E5
gpg pgp.mit.edu 7EFE74E5
Время от времени стоит обновлять ключи, на случай, если у ключей появились новые подписи, или какие-то ключи отозвали:
Пример шифрования и подписи файла для заданного получателя (ключ -r можно указывать много раз):
Расшифровка файла и проверка подписи осуществляется командой:
Пример подписи и проверки подписи бинарного файла (например, ISO образа диска):
gpg file.iso
gpg file.iso.sig
Симметричное шифрование/дешифрование файла (удобно, например, для хранения паролей):
gpg nonsense.gpg AES nonsense.txt
gpg nonsense2.txt nonsense.gpg
Симметричное шифрование с сохранением в бинарном формате (удобно для шифрования бэкапов):
Расшифровка зашифрованного таким образом файла:
При этом по умолчанию GPG запрашивает пароль через GUI интерфейс, что я лично нахожу не очень-то удобным. Изменить данное поведение можно так:
Может оказаться, что ваш закрытый ключ скомпрометирован, то есть, его украли и подобрали к нему пароль. Или же вы потеряли его. Или просто не можете вспомнить пароль от ключа. Для таких случаев предусмотрен отзыв ключа. Делается это так. Заранее, сразу после создания ключей, требуется создать сертификат отзыва:
Используя его, ключ можно отозвать так:
gpg revocation.crt
gpg pgp.mit.edu 7EFE74E5
Важно! Сертификат отзыва не шифруется и может быть использован кем угодно. Убедитесь, что храните его в надежном месте (лучше даже в нескольких таких местах) и непременно в зашифрованном виде!
Прикручиваем GnuPG к Claws Mail
В Ubuntu нам понадобятся следующие пакеты:
В свойствах аккаунта во вкладке Privacy можно настроить плагины так, чтобы сообщения всегда подписывались, шифровались при ответе на зашифрованные сообщения, и так далее. Использовать советую PGP/MIME, так как PGP/Inline может не слабо раздражать пользователей, не использующих PGP/GPG. То есть, почти всех.
Из косяков плагина я столкнулся только с тем, что в настройках нужно указать полный путь к исполняемому файлу gpg, после этого все заработало.
Прикручиваем GnuPG к Mutt
Чтобы GPG заработал в Mutt, в ~/.muttrc дописываем:
# включаем поддержку GPG
set crypt_use_gpgme=yes
# по дэфолту подписывать все сообщения
set crypt_autosign=yes
# шифровать ответы на зашифрованные сообщения
set crypt_replyencrypt=yes
При написании письма жмем , там выбираем опции — подписать, зашифровать, и так далее. Все опции и описаны в . Плюс к этому здесь есть длинная строчка, благодаря которой Mutt можно научить проверять подписи для inline сообщений.
Мой полный и поддерживаемый в актуальном состоянии вариант конфига для Mutt находится здесь.
Заключение
GPG прикручивается еще очень много к чему. Скажем, для Thunderbird есть плагин Enigmail. Существуют мобильные приложения с поддержкой GPG. Например, для iPhone есть oPenGP и iPGMail. Кроме того, существуют плагины и для IM-клиентов, в частности, для Psi. К сожалению, рассмотреть их все в рамках одной статьи не представляется возможным.
В качестве домашнего задания можете добавить меня в свой keyring, подписать мои ключи и отправить мне на email зашифрованное письмо.
А используете ли вы PGP/GPG?
Дополнение: Также вас может заинтересовать статья Шифрование сообщений в Jabber при помощи OTR.
Метки: Безопасность, Криптография.
Для создания и манипуляций с архивами в Linux-дистрибутивах используется утилита командной строки tar. C помощью этой утилиты можно как извлечь данные из файлов tar, pax, cpio, zip, jar, ar и даже ISO (образы cdrom), так и создать соотвествующие архивы.
Чаще всего используются следующие опции данной утилиты:
- -j – использовать сжатие архива с помощью bzip2;
- -v – запуск команды в режиме verbose – для просмотра прогресса выполнения;
- -f – указание имени архива;
- -W – верификация архива;
- -z – использовать сжатие архива с помощью gzip;
- -t – просмотр содержимого архива;
- -c – создание нового архива;
- -r – добавление или обновление файлов или каталогов в уже существующий архив;
- -u – аналог опции -r, но данные добавляются только если у них более поздняя дата модификации;
- -x – извлечение данных из архива.
tar -cvf /path/to/foo.tar /path/to/foo/
Примечание. Можно использовать абсолютные пути к файлам, вместо относительных, как в примере выше.
tar -czvf /path/to/foo.tgz /path/to/foo/
tar -cjvf /path/to/foo.tgz /path/to/foo/
tar -zcvf /path/to/foo.tgz -C/path/to/foo .
tar -cvf fullbackup.tar i*
tar –append –filebackup.tar anaconda-ks.cfg
tar –concatenate –filebackup.tar fullbackup.tar
tar -xvf /path/to/foo.tar
tar -xzvf /path/to/foo.tgz
tar -xjvf /path/to/foo.bz2
tar -xvf /path/to/foo.tar -C /path/to/destination/
tar –extract -vv –occurrence –file./backup.tar anaconda-ks.cfg
tar -ztvf /path/to/foo.tgz
tar -jtvf /path/to/foo.tgz
tar -cvhf /path/to/foo.tar /path/to/foo/
Консольная утилита tar – одна из наиболее часто используемых в мире Linux – будет полезна при создании резервных копий, установке пакетов, обмене файлами, шифровании и дешифровке данных.
English
Chinese Simpl.
Chinese Trad.
Esperanto
French
German
Indonesian
Japanese
Persian
Portuguese Brazil
Spanish
Thai
Vietnamese
Download 7-Zip 22.01 (2022-07-15):
Download 7-Zip 21.07 (2021-12-26):
Download 7-Zip 19.00 (2019-02-21) for Windows:
Download 7-Zip 16.04 (2016-10-04) for Windows:
Download 7-Zip 9.20 (2010-11-18) for Windows:
You can download any versions of 7-Zip (including latest beta versions) from SourceForge:
7-Zip files at SourceForge
7-Zip at SourceForge
Download p7zip for Linux (Posix) (x86 binaries and source code):
p7zip at SourceForge
p7zip is the command line version of 7-Zip for Linux / Unix, made by an independent developer.
Some unofficial p7zip packages for Linux and other systems:
Tar и Gzip – пакеты, которые присутствуют во всех Linux-дистрибутивах, этого уже достаточно для того, чтобы знать, как работать с архивами .tar.gz в разных операционных системах.
tar – утилита, которая не “умеет” сжимать, но запаковывает множество файлов в один, при этом, сохраняя структуру каталогов
gzip – утилита, предназначенная для сжатия одного файла.
bzip2 – утилита, по функционалу аналогичная gzip, использует другой алгоритм сжатия
Исходя из особенностей работы данных утилит, их используют в паре (упаковываем и сжимаем)
Рассматривать примеры упаковки/распаковки будем на примере Ubuntu
1 Основные параметры командной строки
-c – создание нового архива
-j – использовать алгоритм сжатия bzip2
-z – использовать алгоритм сжатия gzip
-f – указываем имя архивного файла, с которым работаем
-t – просмотр содержимого без распаковки
-r – добавление в уже существующий архив
-x – распаковка архива
-v – вывод результата работы. При создании/распаковке выводит перечень файлов. При просмотре содержимого архива детальный вывод аналогично ls -l
1 Упаковка файлов
Создание архива my_arch.tar.gz и добавление в него директории /home/home/myfolder
tar -cvzf my_arch.tar.gz /home/home/myfolder
Создание архива my_arch.tar.gz и добавление в него файлов file1 file2 file3
tar -cvzf my_arch.tar.gz file1 file2 file3
Добавление к существующему архиву my_arch.tar.gz файлов file1 file2 file3
tar -rvzf my_arch.tar.gz file1 file2 file3
2 Просмотр содержимого архива
Просмотр содержимого my_arch.tar.gz без его распаковки
tar -tvf my_arch.tar.gz
3 Распаковка архива
Распаковка архива my_arch.tar.gz в текущую директорию
tar -xvf my_arch.tar.gz
Распаковка архива my_arch.tar.gz в директорию /home/home/myfolder
tar -xvf my_arch.tar.gz /home/home/myfolder
Работа с архивами в Windows
В среде Windows создание архива .tar.gz происходит в 2 этапа (действия с архиватором).
Сразу упаковываем файлы/директории в tar-контейнер (рис 1), потом сжимаем созданный tar-контейнер, на этом этапе нам станут доступны к выбору методы сжатия (формат архива) gzip и bzip2 (рис 2)
2 Распаковка архива
Просматривать и распаковывать архив рекомендую с помощью 7zip. Также данный формат поддерживает для распаковки WinRAR.
I would like to unzip Filename.tar.gz to Filename using single command in windows batch script
All the files inside zip should go inside the Filename Folder
I am trying to do in windows . I am not getting correct output.
Can anyone suggest an idea
asked Dec 5, 2014 at 12:36
Windows Command line now supports tar from Windows 10 insider build 17063. You may try run the below command in cmd or PowerShell to see if it works:
tar xzvf your-file-name.tar.gz
answered May 22, 2019 at 15:10
1 gold badge6 silver badges17 bronze badges
7 zip can do that: http://www.7-zip.org/
It has a documented command line. I use it every day via scripts.
Plus: it is free and has 32 and 64 bit versions.
answered Dec 5, 2014 at 12:41
20 silver badges33 bronze badges
Windows 10 command line supports tar command
Write the tar command as general to the Linux terminal.
tar -zxvf tar-filename.tar.gz –directory destination-folder
answered Mar 12, 2022 at 18:19
in windows compand promt use quotation marks (“”) when specifying the path. It will work properly
Exaple : tar -xvzf “C:/PATH/TO/FILE/FILE-NAME.tar.gz” -C “C:/PATH/TO/FOLDER/EXTRACTION”
answered Dec 1, 2022 at 20:51
A Tape Archive file, or TAR, for short, is a way to package source code for downloading purposes or bootable ISO image. The basic .tar files are uncompressed, but they can be compressed into .tar.gz or .tar.bz2 to take up even less space. In a Linux environment, .tar is the de facto standard for making source code available for download, but you can so unzip it in Windows and Mac if needed. This article shows you how to do it in detail steps..
How to Unzip or Unpack. tar. gz or. tar. bz2 File on Windows 10
Step 3: Put the file to be extracted into the destination directory. Open CMD and cd to that directory. Then, if the file is compressed, run one of these commands: 7z x filename.tar.gz
Step 4: You either have to run both commands or just the second one. The first one can be replaced with filename.tar.bz2 or whatever the name of your TAR file. The file will download into a directory within the directory with all your files extracted.
Step 5: Using the 7-Zip GUI is easier for most people, so if you want to do that, use the File Manager to simply open the file and 7-Zip will do the rest.
How to Extract or Uncompress. tar. gz or. tar. bz2 File on Mac
Step 1: First of all, move the .tar.gz or .tar.bz2 file to a directory that you can remember.
Step 2: Make sure you have a Terminal shell running, then go to the directory where the TAR file was copied.
Both Windows and Mac have the default tools required to extract TAR GZ files but, as you can see, most of them require a little hands-on experience in Command Prompt or Terminal. You can also choose a premium file compression utility and easily get it to do the job in a couple of clicks, but it’s good to be aware of free methods and tools in case you’re in a pinch and need to urgently unpack .tar.gz and .tar.bz2 file.
Petty is editor in chief at UUByte and writes various topics about Windows and Mac to help people make the most of current technology.
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.
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.
Compressing and extracting files isn’t always intuitive. 😅 Learn how to unzip .tar.gz files in Linux and Windows with help from this guide 🚀Click to Tweet
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.
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.
Extract .tar.gz file to current working directory:
tar -xf filename.tar.gz
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:
tar -xvf filename.tar.gz
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:
tar -xf filename.tar.gz file1 directory1
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:
tar -xf filename.tar.gz –wildcards ‘*.txt’
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:
tar -tvf filename.tar.gz
List detailed contents of a .gz file with gzip:
gzip -l filename
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.
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:
gzip -d filename.tar
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:
gzip -c filename.tar
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:
gzip file1 file2
Decompress multiple files:
gzip -d file1 file2
Compress all files in a directory:
gzip -r directory1
Decompress all files in a directory:
gzip -dr directory1
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.
Using the Command Line (cmd)
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.
tar -xvzf filename.tar.gz
Extract .tar.gz file from source path to destination path:
tar -xvzf C:PATHTOSOURCEilename.tar.gz -C C:PATHTODESTINATION
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
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.
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.
Not found in archive
This error occurs when trying to extract specific files or directories from a .tar.gz file using tar.
tar: FILE: Not found in filename
tar: Exiting with failure status due to previous errors
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.
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.
Notice that the “-z” is missing from what should be sudo tar -xz on the far right.
tar: Archive is compressed. Use -z option
tar: Error is not recoverable: exiting now
Solution: Specify a decompression option such as gzip (-z) in the tar command.
Not in gzip format
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error exit delayed from previous errors
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.
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.
tar: Unrecognized archive format
tar: Error exit delayed from previous errors.
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.
FAQs
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.
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.
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.
Need a little help extracting files? This guide is here to help ✅Click to Tweet
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.
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
- 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.
Хотя чаще всего мы говорим о ZIP или RAR, когда говорим о сжатых файлах, это происходит только потому, что мы обычно перемещаемся в среде Windows. Если мы знакомы с другими операционными системами Linux или Unix, сжатые файлы обычно имеют другие расширения. К счастью, это не проблема для Windows который может справиться с ними либо своими собственными командами, либо с помощью доверенных сторонних приложений.
Пользователи Linux, Unix или macOS больше привыкли к этим типам файлов. В случае дегтя (от англ. «Tape ARchiver») мы имеем дело с форматом файлов среды UNIX, который используется для хранения файлов и каталогов в одном файле, но не для их сжатия. Используя программы сжатия, такие как gzip, bzip2, xz, lzip, lzma или compress, мы получаем файлы с такими расширениями, как .tgz или .tar.gz, .tbz, .tbz2, .tb2 или .tar.bz2, .taz, .tz или .tar.Z, .tlz или .tar.lz, .tar.lzma и .txz или .tar.xz для их расширений.
Деготь широко используется в Среды UNIX и его файлы обозначаются суффиксом файла .tar. В этом случае мы не говорим о сжатых файлах, поскольку в этом случае .tar.gz будет результирующим файлом при сжатии с помощью gzip. Это также может называться .tgz в его сокращенной версии расширения.
Формат tar был стандартизирован POSIX.1-1998 и позже POSIX.1-2001. Кроме того, будучи разработанными для Unix, эти файлы хранят всю метаинформацию, связанную с файлами, включенными в эти операционные системы (дата последнего изменения, владелец и разрешения), в том же формате, что и система UNIX.
Работа с. tar. tar. tgz. gz в Windows
К счастью, появляется все больше и больше приложений, которые мы можем использовать для сжатия и распаковки этих файлов. В Windows 10 мы рекомендуем использовать 7-Zip и PeaZip . Хотя существует гораздо больше альтернатив, мы увидим, как работать с этими типами файлов в этих двух приложениях.
PeaZip
Во-первых, мы увидим, как мы можем «объединить» эти файлы, чтобы несколько файлов были объединены в одно, со сжатием или без сжатия с помощью популярного диспетчера сжатых файлов PeaZip. Он поддерживает почти все типы сжатых файлов, до почти 200 различных форматов , а также предоставляет другие интересные функции для управления всеми файлами в сжатых архивах.
Сжать. tar. tar. tgz. gz с помощью PeaZip
Для этого у нас должен быть установлен PeaZip на компьютере, и мы должны выполнить несколько простых шагов:
- Откройте PeaZip
- Найдите файлы для сжатия
- Выделите их мышью
- Щелкните правой кнопкой мыши выбранные файлы и «Добавить в файл»
- В первом раскрывающемся списке выберите GZip для tar.gz или TAR для .tar.
- Принять
Разархивируйте. tar. tar. tgz. gz с помощью PeaZip
Процесс «извлечения» файлов, содержащихся в этом архиве, аналогичен, но в обратном порядке, в частности:
- Правая кнопка на сжатом файле
- Мы также можем нажать «Открыть как архив», чтобы открыть PeaZip и просмотреть его содержимое.
Как мы видим, простые шаги по сжатию или распаковке этих наиболее распространенных форматов в среде UNIX в Windows 10, но которые можно найти на нашем компьютере в любое время.
7-Zip
Еще одна альтернатива, которая у нас есть, – это сделать это с помощью 7-Zip, другого бесплатного компрессора, преимущественно используемого для операционной системы компании из Редмонда. Один из лучших бесплатных компрессоров и декомпрессоров с открытым исходным кодом, доступных на сегодняшний день. Это обеспечивает совместимость со всеми основными форматами и предлагает возможность сжимать файлы во многих различных форматах.
Сжать. tar. tar. tgz. gz с помощью 7-Zip
В этом случае мы сможем напрямую создавать только файлы .tar и .gz. Для этого мы выполним следующие шаги:
- Открыть 7-Zip
- Найдите файлы для сжатия
- Выделите их мышью
- В раскрывающемся списке “Формат файла” выберите tar или gzip.
- Принять
Разархивируйте. tar. tar. tgz. gz с помощью 7-Zip
- Правая кнопка на сжатом файле
- Мы также можем нажать «Открыть как архив», чтобы открыть 7-Zip и просмотреть его содержимое.
Используйте CMD или командную строку Windows
К счастью, операционная система Windows скрывает возможность распаковки файлов .tar .tar.gz .tgz .gz из командной строки с помощью команды tar. Для этого откроем CMD или командную строку с разрешением администратора . После открытия нам нужно будет ввести следующую команду:
tar -xvzf C: test.tar -CC: тест
Мы изменим C: test.tar на точное расположение файла на нашем жестком диске и C: test на точное расположение папки, в которую мы хотим извлечь содержимое. Важно, чтобы эта папка назначения была создана заранее, поскольку, если она не будет создана, команда вернет сообщение «Tar: не смог chdir на ‘C: test’».
На предыдущем изображении мы видим, как все содержимое файла .tar было извлечено в это новое место без необходимости установки какой-либо сторонней программы или приложения. Однако две упомянутые альтернативы, такие как PeaZip и 7-Zip, являются полностью надежный , бесплатные приложения с миллионами пользователей, которые не создают проблем для нашего компьютера.