- Extract tar.gz File in Linux or Unix using tar
- Syntax to extract .tar.gz file
- Extracting tr.gz. file
- Extracting an entire archive
- List files in archive
- How to create a tarball
- How to add files to an existing tarball
- How delete files from a tarball
- Conclusion
- Команда tar в Linux
- Синтаксис команды tar
- Как пользоваться tar
- 1. Создание архива tar
- 2. Просмотр содержимого архива
- 3. Распаковка архива tar Linux
- 3. Работа со сжатыми архивами
- Выводы
- How to Extract Tar Files to Specific or Different Directory in Linux
- Example 1: Extracting tar Files to a Specific Directory
- Example 2: Extract .tar.gz or .tgz Files to Different Directory
- Example 3: Extract tar.bz2, .tar.bz, .tbz or .tbz2 Files to Different Directory
- Example 4: Extract Only Specific or Selected Files from Tar Archive
- Summary
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Extract tar.gz File in Linux or Unix using tar
I have downloaded a file called foo.tar.gz from the Internets. How do I extract tar.gz file under Linux / UNIX like operating systems using command line options?
A tarball (tar.gz file) is nothing but compressed tar archive. The tar program provides the ability to create tar archives, as well as various other kinds of manipulation. For example, you can use tar on previously created archives to extract files, to store additional files, or to update or list files which were already stored.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | tar |
Est. reading time | 2m |
Initially, tar archives were used to store files conveniently on magnetic tape. The name “Tar” comes from this use; it stands for tape archiver. Despite the utility’s name, Tar can direct its output to available devices, files, or other programs (using pipes), it can even access remote devices or files as archives. The tar command is available on Linux (CentOS/RHEL/Fedora/Debian/Ubuntu and all other distros), BSD (OpenBSD/NetBSD/FreeBSD), Apple macOS, HP-UX, AIX, and other Unix-like operating systems. This page shows how to extract tar.gz file using command line.
Syntax to extract .tar.gz file
The syntax is as follows:
Extracting tr.gz. file
To extract one or more members from an archive, enter:
$ tar -zxvf < file.tar.gz >
If your tarball name is backup.tar.gz, enter the following at a shell prompt to extract files:
$ tar -zxvf backup.tar.gz
To extract resume.doc file from backup.tar.gz tarball, enter:
$ tar -zxvf backup.tar.gz resume.doc
Where,
- -z : Work on gzip compression automatically when reading archives.
- -x : Extract tar.gz archive.
- -v : Produce verbose output i.e. display progress and extracted file list on screen.
- -f : Read the archive from the archive to the specified file. In this example, read backups.tar.gz archive.
- -t : List the files in the archive.
- -r : Append files to the end of the tarball.
- —delete (GNU/Linux tar only) : Delete files from the tarball.
In order to untar a tar file, the -x (for extract) and -f options are needed.
Extracting an entire archive
To extract an entire archive, specify the archive file name only, with no individual file names as arguments.
tar -zxvf backup.tar.gz
List files in archive
To view a list of the files within a tarball, issue the following command, enter:
$ tar -tvf backup.tar.gz
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
How to create a tarball
tar command used to create a Tape ARchive. The resulting file is known as a tarball in Unix world. Let us see how to create a tarball using tar command. The following would create an archive file called data.tar from the three files named file1.txt, file2.txt and file3.txt that are located in the current directory:
tar -cvf data.tar file1.txt file2.txt file3.txt
One can use the tar command to make archives from the contents of one or more directories. For example, the contents of two directories named /etc/ and /home/vivek/Documents/ could be archived into a file named dump.tar with the following:
tar -cvf dump.tar /etc/ /home/vivek/Documents
In this example, create an archive named data.tar.bz2 of the files /etc/ directory that is compressed using gzip:
tar -cvzf files.tar.gz /etc/
How to add files to an existing tarball
Pass the -r option. For example, the following would append a file named resume.doc to file.tar:
tar -rf file.tar resume.doc
How delete files from a tarball
Pass the —delete option to GNU/tar command which allows specified files to be completely removed from a tarball. Thus, for example, the files pic1.png and pic2.png can be removed from file.tar with the following:
tar -f file.tar —delete pic1.png pic2.png
Conclusion
We have shown you how to extract tar.gz file from the command line. The commands should work on Linux and Unix-like systems. For more info see tar command help page here and here.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Команда tar в Linux
В качестве инструмента для архивации данных в Linux используются разные программы. Например архиватор Zip Linux, приобретший большую популярность из-за совместимости с ОС Windows. Но это не стандартная для системы программа. Поэтому хотелось бы осветить команду tar Linux — встроенный архиватор.
Изначально tar использовалась для архивации данных на ленточных устройствах. Но также она позволяет записывать вывод в файл, и этот способ стал широко применяться в Linux по своему назначению. Здесь будут рассмотрены самые распространенные варианты работы с этой утилитой.
Синтаксис команды tar
Синтаксис команд для создания и распаковки архива практически не отличается (в том числе с утилитами сжатия bzip2 или gzip). Так, чтобы создать новый архив, в терминале используется следующая конструкция:
tar опции архив.tar файлы_для_архивации
Для его распаковки:
tar опции архив.tar
Функции, которые может выполнять команда:
Функция | Длинный формат | Описание |
---|---|---|
-A | —concatenate | Присоединить существующий архив к другому |
-c | —create | Создать новый архив |
-d | —diff —delete | Проверить различие между архивами Удалить из существующего архива файл |
-r | —append | Присоединить файлы к концу архива |
-t | —list | Сформировать список содержимого архива |
-u | —update | Обновить архив более новыми файлами с тем же именем |
-x | —extract | Извлечь файлы из архива |
При определении каждой функции используются параметры, которые регламентируют выполнение конкретных операций с tar-архивом:
Параметр | Длиннный формат | Описание |
---|---|---|
-C dir | —directory=DIR | Сменить директорию перед выполнением операции на dir |
-f file | —file | Вывести результат в файл (или на устройство) file |
-j | —bzip2 | Перенаправить вывод в команду bzip2 |
-p | —same-permissions | Сохранить все права доступа к файлу |
-v | —verbose | Выводить подробную информацию процесса |
—totals | Выводить итоговую информацию завершенного процесса | |
-z | —gzip | Перенаправить вывод в команду gzip |
А дальше рассмотрим примеры того, как может применяться команда tar Linux.
Как пользоваться tar
1. Создание архива tar
С помощью следующей команды создается архив archive.tar с подробным выводом информации, включающий файлы file1, file2 и file3:
tar —totals —create —verbose —file archive.tar file1 file2 file3
Но длинные опции и параметры можно заменить (при возможности) однобуквенными значениями:
tar —totals -cvf archive.tar file1 file2 file3
2. Просмотр содержимого архива
Следующая команда выводит содержимое архива, не распаковывая его:
tar -tf archive.tar
3. Распаковка архива tar Linux
Распаковывает архив test.tar с выводом файлов на экран:
tar -xvf archive.tar
Чтобы сделать это в другой каталог, можно воспользоваться параметром -C:
tar -C «Test» -xvf archive.tar
3. Работа со сжатыми архивами
Следует помнить, что tar только создаёт архив, но не сжимает. Для этого используются упомянутые компрессорные утилиты bzip2 и gzip. Файлы, сжатые с их помощью, имеют соответствующие расширения .tar.bz2 и .tar.gz. Чтобы создать сжатый архив с помощью bzip2, введите:
tar -cjvf archive.tar.bz2 file1 file2 file3
Синтаксис для gzip отличается одной буквой в параметрах, и меняется окончание расширения архива:
tar -czvf archive.tar.gz file1 file2 file3
При распаковке tar-архивов с таким расширением следует указывать соответствующую опцию:
tar -C «Test» -xjvf arhive.tar.bz2
tar -xzvf archive.tar.gz
На заметку: архиватор tar — одна из немногих утилит в GNU/Linux, в которой перед использованием однобуквенных параметров, стоящих вместе, можно не ставить знак дефиса.
Выводы
В этой статье была рассмотрена команда tar Linux, которая используется для архивации файлов и поставляется по умолчанию во всех дистрибутивах. В её возможности входит создание и распаковка архива файлов без их сжатия. Для сжатия утилита применяется в связке с популярными компрессорами bzip2 и gzip.
Источник
How to Extract Tar Files to Specific or Different Directory in Linux
The tar utility is one of the utilities that you can use to create a backup on a Linux system. It includes many options that one can use to specify the task to achieve.
Extract Linux Tar Files Different or New Directory
One thing to understand is that you can extract tar files to a different or specific directory, not necessarily the current working directory. You can read more about tar backup utility with many different examples in the following article, before proceeding further with this article.
In this guide, we shall take a look at how to extract tar files to a specific or different directory, where you want the files to reside.
The general syntax of tar utility for extracting files:
Note: In the above first syntax, the -C option is used to specify a different directory other than the current working directory.
Let us now look at some examples below.
Example 1: Extracting tar Files to a Specific Directory
In the first example, I will extract the files in articles.tar to a directory /tmp/my_article . Always make sure that the directory into which you want to extract tar file exists.
Let me start by creating the /tmp/my_article directory using the command below:
You can include the -p option to the above command so that the command does not complain.
To extract the files in articles.tar to /tmp/my_article , I will run the command bellow:
Img 01: Extract Tar Files to Different Directory
In the above example I used the -v option to monitor the progress of the tar extraction.
Let me also use the —directory option instead of -c for the example above. It works just in the same way.
Img 02: Extract Tar Files to Specific Directory
Example 2: Extract .tar.gz or .tgz Files to Different Directory
First make sure that you create the specific directory that you want to extract into by using:
Now we will extract the contents of documents.tgz file to separate /tmp/tgz/ directory.
Img 03: Extract tar.gz or .tgz Files to Different Directory
Example 3: Extract tar.bz2, .tar.bz, .tbz or .tbz2 Files to Different Directory
Again repeating that you must create a separate directory before unpacking files:
Now we will be unpacking the documents.tbz2 files to /tmp/tar.bz2/ directory.
Img 04: Extract tar.bz2 Files to Different Directory
Example 4: Extract Only Specific or Selected Files from Tar Archive
The tar utility also allows you to define the files that you want to only extract from a .tar file. In the next example, I will extract specific files out of a tar file to a specific directory as follows:
Img 05: Extract Specific Files From Tar Archive
Summary
That is it with extracting tar files to a specific directory and also extracting specific files from a tar file. If you find this guide helpful or have more information or additional ideas, you can give me a feedback by posting a comment.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник