Extracting tar in linux

Команда 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.xz files in Linux and unzip all files

H ow do I extract tar.xz files in Linux? Can you tell me command to unzip linux-5.6.13.tar.xz file? How can I uncompressing (or decompressing) all files in the current directory?

The tar command and xz command provides support for extracting and uncompressing tar.xz files and .txz archives under Linux operating systems.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements tar and xz commands on Linux
Est. reading time 6 minutes

How do I extract tar.xz files in Linux?

  1. Install xz using the dnf install xz on a CentOS/RHEL/Fedora Linux.
  2. Debian/Ubuntu Linux users try apt install xz-utils command.
  3. Extract tar.xz using the tar -xf backup.tar.xz command
  4. To decompress filename.tar.xz file run: xz -d -v filename.tar.xz

Installation

XZ is a set of open-source software for lossless data compressors, including LZMA and xz formats. These formats are popular among open source developers and projects due to higher compression rates than alternatives tools like gzip and bzip2. The tar command works if xz installed on the system. Hence, we must install it.

Debin/Ubuntu Linux install xz

Use the apt command/apt-get command:
$ sudo apt install xz-utils
Sample outputs:

CentOS/RHEL/Fedora Linux install xz

Open the terminal app and then run NA command/dnf command as follows:
$ sudo dnf install xz
## On an older version of CentOS/RHEL try yum ##
$ sudo yum install xz
From my CentOS 6.x box:

Installing xz on OpenSUSE/SUSE Enterprise Linux

We can use the zypper command to install xz:
$ sudo zypper install xz

OpenSUSE installing xz package for extraction purposes

Examples

Now we install xz. We can now directly use the tar command as follows for extracting a file named linux-5.6.13.tar.xz:
$ tar -xf linux-5.6.13.tar.xz
$ tar -xvf linux-5.6.13.tar.xz
$ tar -Jxvf linux-5.6.13.tar.xz
## extract tar.xz files aka .txz file ##
$ tar —xz -xf archive.txz

Extracting specific files from a tar.xz file

We extract a given file names from a backup.tar.xz file by using the following syntax:
$ tar -xf backup.tar.xz resume.pdf
$ tar -xf backup.tar.xz babys-3rd-cake-day.jpg sales.txt
Sometimes we don’t know file names in advance. Hence, we list the contents of an archive by passing the -t as follows and then unzip tar.xz files:
$ tar -tvf backup.tar.xz
## filter out tar listing option using the grep command/egrep command ##
$ tar -tvf backup.tar.xz | grep file1
$ tar -tvf backup.tar.xz | egrep ‘ file.txt | data.doc | cake.jpg ‘

Want to extract all Perl or Python source code files? Try the following option:
$ tar —wildcards ‘*.py’ -xvf webroot.tar.xz
$ tar —wildcards ‘*.pl’ -xvf centos-7-sysadmin-scripts.txz

Understanding tar command options

  • -x : Extract/get/unzip files from an archive.
  • -f archive.tar.xz : Use this archive file or device archive for extracting files
  • -J OR —xz : Filter the archive through xz command. Hence, we install xz using package manager.
  • -v : Verbose. Show progress.
  • -t : List file stored inside .tar.xz/.xz archive.
  • —wildcards : By default, wildcards don’t work as they treated or processed to by your current shell. Therefore, to extract files, use the —wildcards options. For example, extract all .webp images I would pass —wildcards ‘*.webp’ option to the tar.

How to extract .xz files using the xz command

So far, we learned to use tar for extracting. But, we can use xz command directly for as compressor and decompressor too. Tar internally calls xz itself or using API provided by libs. Let us see some tips and tricks for xz command.

Decompress .tar.xz file

$ xz —decompress filename.tar.xz
$ xz -v -d archives.tar.xz
Decompress file named mysql.sql.xz and replaced by mysql.sql:
$ xz -v -d mysql.sql.xz

Compress tarball as .tar.xz file

Compress a file named mysql.sql and replace it by mysql.sql.xz for saving disk space:
$ xz mysql.sql
The syntax is as follows for compressing per-existing tarball:
$ xz -v -z filename.tar
Alternatively, use the tar command for convenience purposes
$ tar -cv J f file1 file2
$ tar -cv J f /path/to/dir1 ./dir2
$ sudo tar -cv J f /efs/backups/14-05-2020/production-webroot.tar.xz /var/www/
$ sudo tar —xz -cvf /efs/backups/aws-us-west-www-prod-42-etc.txz /etc/

Gif 01. xz in action

Compress from stdin

$ mysqldump nixcraft-blog | xz > nixcraft-blog.sql.xz
Of coruse we can uncompress and send content to stdout for the mysql command too
$ xzcat nixcraft-blog.sql.xz | mysql nixcraft-blog
Let us uncompress tar directory from stdin sent from the nc, enter (assuming that target server-ip protected by VPN else use the ssh command):
$ nc -l -p 4242 | tar -xJvf —
On other side compress directory to stdout and send to the nc, run:
$ tar -cJvz — /var/www/html | nc server-ip-here 4242
Our final example use ssh instead of nc:
$ tar —xz -cf — /path/to/dir | ssh vivek@server1.cyberciti.biz «cat > filename.txz»
See “How To Use tar Command Through Network Over SSH Session” for more info.

  • 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

Conclusion

This quick tutorial explained how to extract and unzip popular archive formats such as .tar.xz and .txz under Linux operating systems. Remember, tar command only works if you install the xz command via the package manager. See the xz project home page and docs here.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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,

  1. -z : Work on gzip compression automatically when reading archives.
  2. -x : Extract tar.gz archive.
  3. -v : Produce verbose output i.e. display progress and extracted file list on screen.
  4. -f : Read the archive from the archive to the specified file. In this example, read backups.tar.gz archive.
  5. -t : List the files in the archive.
  6. -r : Append files to the end of the tarball.
  7. —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

Источник

Читайте также:  Linux mint ставить или нет
Оцените статью