Использование tar в Linux и FreeBSD для работы с архивами
Утилита командной строки tar используется для работы с архивами в операционных системах на базе UNIX. С ее помощью можно архивировать данные и оптимизировать использование дискового пространства.
Создание и распаковка архивов
Рассмотрим общий синтаксис для создания и распаковки архивов.
Создать
Создание выполняется с ключом c. Синтаксис следующий:
tar -c<опции> <новый архивный файл> <что сжимаем>
tar -czvf archive.tar.gz /home/dmosk
* в данном примере будет создан архив archive.tar.gz домашней директории пользователя (/home/dmosk)
** где z — сжать архив в gzip (без этого параметра, tar не сжимает, а создает так называемый тарбол); c — ключ на создание архива; v — verbose режим, то есть с выводом на экран процесса (очень удобно для наблюдением за ходом работы, но в скриптах можно упустить); f — использовать файл (обязательно указываем, так как в большей степени работаем именно с файлами).
Распаковать
Распаковка выполняется с ключом x с синтаксисом:
tar -x<опции> <архивный файл>
tar -xvf archive.tar.gz
Форматы
Утилита tar позволяет работать с архивами различных форматов. Рассмотрим их кратко.
tar -cf archive.tar.gz /files
Распаковка .gz файла:
tar -xf archive.tar.gz
* при возникновении ошибки This does not look like a tar archive, можно воспользоваться командой gzip -d archive.tar.gz.
tar -xvjf archive.tar.bz2
* ключ j отвечает за работу с bz2.
Если система ругается на bzip2, значит нужно его установить:
yum install bzip2
apt-get install bzip2
pkg install bzip2
* соответственно, для CentOS (RPM based), Ubuntu (deb based), FreeBSD (BSD based).
Если видим ошибку tar: Unrecognized archive format, воспользуемся следующей командой:
bzip2 -d archive.tar.bz2
tar -xvzf archive.tar.gzip
* ключ z отвечает за работу с gzip.
TGZ — tar-архив, сжатый с помощью утилиты gzip. По сути, это тот же tar.gz, и работа с ним ведется такими же командами. Рассмотрим примеры работы с данным форматом.
Для создания архива tgz выполняем:
tar -czf archive.tgz /files
Распаковывается, как gzip:
tar -xzf archive.tgz
Это формат сжатия данных с помощью алгоритма LZMA. Для работы с ним устанавливаем:
apt install xz-utils
* на Debian / Ubuntu.
* на Rocky Linux / CentOS.
Теперь можно пользоваться.
tar -cpJf archive.tar.xz /home/user
tar -xpJf archive.tar.xz
Описание ключей tar
Команды для действия
Ключ | Описание |
---|---|
-A | Добавление файлов в архив. |
-c | Создание нового архивного файла. |
-d | Показать отличающиеся данные между каталогом-исходником и содержимым архива. |
—delete | Удалить файлы внутри архива. |
-r | Добавить файлы в конец архива. |
-t | Показать содержимое архива. |
-u | Добавить файлы, которых нет в архиве. |
-x | Извлечь файлы из архива. |
* нельзя использовать несколько вышеперечисленных ключей в одной команде.
Дополнительные опции
Ключ | Описание |
---|---|
—atime-preserve | Оставить прежнюю метку времени доступа для файла. |
-b N | Задать размер блока N x 512. |
-C | Смена каталога. По умолчанию, используется тот, в котором мы находимся. |
—checkpoint | Показать имена папок при чтении архивного файла. |
-G | Использование старого формата инкрементального резервирования при отображении или извлечения. |
-g | Использование нового формата инкрементального резервирования при отображении или извлечения. |
-h | Не дублировать символьные ссылки. Только файлы, на которые указывают эти симлинки. |
-i | Игнорировать блоки нулей. |
-j | Использование bzip2. |
—ignore-failed-read | Игнорировать не читаемые файлы. |
-k | При распаковке, существующие файлы не заменяются соответствующими файлами из архива. |
-L N | Смена магнитной ленты после N*1024 байт. |
-m | При извлечении игнорировать время модификации объекта. |
-M | Многотомные архивы. |
-N DATE | Сохранять только более новые файлы относительно DATE |
-O | Направление извлекаемого на стандартный вывод. |
-p | Извлечение защищенной информации. |
-P | Не отбрасывает начальный слэш (/) из имен. |
-s | Сортировка файлов при извлечении. |
—preserve | Аналогично -ps |
—remove-files | Удалить исходные файлы после добавления в архив. |
—same-owner | Сохранить владельца при извлечении. |
—totals | Вывод байт при создании архива. |
-v | Протоколирование действий — отображение списка объектов, над которыми происходит действие. |
-V NAME | Создание архива на томе с меткой NAME. |
—version | Показать версию tar. |
-w | Требовать подтверждения для каждого действия. |
-W | Проверка архива после записи. |
—exclude FILE | Исключить файл FILE. |
-X FILE | Исключить файлы FILE. |
-Z | Фильтрует архив с помощью compress. |
-z | Использование gzip. |
* актуальный список опций можно получить командой man tar.
Примеры
Рассмотрим некоторые сценарии использования tar.
Распаковать в определенную папку
tar -C /home/user -xvf archive.tar.gz
* ключ -C используется для указания папки, куда необходимо распаковать файлы из архива.
Распаковка без вложенной папки
Такой способ можно использовать для распаковки в заранее подготовленный каталог. Будет некий эффект переименовывания каталога или аналог «Распаковать здесь»:
tar -C /home/admin/mytar -xvf admin.tar.gz —strip-components 1
* каталог /home/admin/mytar заранее должен быть создан; —strip-components 1 пропустит одну вложенную папку внутри архива.
Указать конкретный файл или каталог для распаковки
Если у нас большой архив, но извлечь нужно конкретный файл или каталог, то можно указать его через пробел после указания файла с архивом. Синтаксис:
tar zxf <путь до архива> <что извлечь>
Рассмотрим пример. Напомним, что можно посмотреть содержимое архива с помощью опции t:
tar tf /backup/samba.tar.gz
Теперь можно распаковать архив:
tar -zxf /backup/samba.tar.gz mail
* предположим, что внутри архива samba.tar.gz есть что-то и каталог mail. Извлечем мы только последний.
Исключение файлов по маске
Если необходимо пропустить некоторые файлы, вводим команду с ключом —exclude:
tar —exclude='sess_*' -czvf archive.tar.gz /wwwsite
* в данном примере мы создадим архив archive.tar.gz, в котором не будет файлов, начинающихся на sess_.
Также можно исключить несколько файлов или папок, добавляя несколько опций exclude:
tar —exclude='/data/recycle' —exclude='*.tmp' -zcf /backup/samba/2021-08-29.tar.gz /data/
* в данном примере мы исключим папку recycle и файлы, которые заканчиваются на .tmp
Работа с архивами, разбитыми на части
Разбить архив на части может понадобиться по разным причинам — нехватка места на носителе, необходимость отправки файлов по почте и так далее.
Чтобы создать архив, разбитый на части, вводим команду:
tar -zcvf — /root | split -b 100M — root_home.tar.gz
* данная команда создаст архив каталога /root и разобьет его на части по 100 Мб.
В итоге мы получим, примерно, такую картину:
root_home.tar.gzaa root_home.tar.gzac root_home.tar.gzae
root_home.tar.gzag root_home.tar.gzai root_home.tar.gzab
root_home.tar.gzad root_home.tar.gzaf root_home.tar.gzah
Чтобы собрать архив и восстановить его, вводим команду:
cat root_home.tar.gz* | tar -zxv
Создание tar из отдельных файлов с последующим его архивированием
Мы можем собрать файл tar, добавляя по очереди в него файлы, после чего создать сжатый архив. Предположим, у нас 3 файла: file1, file2, file3.
Сначала создадим tar-файл с первым файлом внутри:
tar -cf ./my_archive.tar ./file1
Следующими двумя командами мы добавим в архив файлы file2 и file3:
tar -rf ./my_archive.tar ./file2
tar -rf ./my_archive.tar ./file3
Сожмем содержимое tar-файла:
gzip < ./my_archive.tar > ./my_archive.tar.gz
Файл tar можно удалить:
rm -f my_archive.tar
Tar не работает с zip-архивами. В системах UNIX для этого используем утилиты zip и unzip. Для начала, ставим нужные пакеты:
yum install zip unzip
apt-get install zip unzip
pkg install zip unzip
* соответственно, для RPM based, deb based, BSD based.
zip -r archive.zip /home/dmosk
* создает архив каталога /home/dmosk в файл archive.zip.
Windows
В системе на базе Windows встроенными средствами можно распаковать только ZIP-архивы. Для работы с разными архивами рекомендуется поставить архиватор, например 7-Zip.
Команда tar: архивация, распаковка и сжатие файлов в Linux
По умолчанию в системах Unix/Linux включен встроенный архиватор tar, позволяющий запаковывать/распаковывать архив и выполнять много других операций с заархивированными файлами. В его функционал не входит компрессия, но он отлично работает с такими утилитами, как Gzip и BZip2 – с помощью них и выполняется сжатие файлов.
В сегодняшней статье мы подробно разберем основные функции команды tar, а также рассмотрим, как работать с архивами в Linux-системе.
Tar: основные функции и синтаксис
Начнем с синтаксиса – он довольно прост. Если вы когда-либо работали в консольном окне, то вопросов возникнуть не должно. Создание нового архива выполняется следующей строчкой кода:
Распаковка файлов тоже выполняется просто:
Основные опции:
- -A, —concatenate – позволяет добавить уже существующий архив к другому;
- -c, —create – создает новый архив и записывает в него файлы;
- -d – расшифровывается как -diff или -delete, где первая команда проверяет различия между архивами, вторая – удаляет данных из архива;
- -r, append – добавляет новые файлы в конец заархивированного документа;
- -t, —list – разрешает посмотреть содержимое архива, формат аналогичен ls –l; если файлы не указаны, то выводит информацию обо всех файлах;
- -u, —update – обновление файлов в созданном архиве с тем же наименованием;
- -x, —extract – распаковывает файлы из заархивированного документа.
Мы также можем использовать особые параметры, относящиеся к каждой опции:
- -c dir, —directory=DIR – перед тем как выполнить операцию, директория будет изменена на dir;
- -f file, —file – выводит результат в file;
- -p, —bzip2 – сохраняет все права доступа;
- -v – расшифровывается как -verbose или -totals: выводит всю информацию о текущем процессе и показывает сведения об уже завершенном процессе.
Как мы говорили ранее, tar также хорошо взаимодействует с утилитами сжатия. Для их использования предназначены отдельные опции:
- -a, -auto-compress – выбирает программу для сжатия данных;
- -I, -use-compress-program=PROG – позволяет фильтровать архив с помощью утилиты PROG, для которой требуется использование опции -d;
- -j, -bzip2 – сжимает архив с помощью программы bzip2;
- -J, -xz – сжимает архив с помощью программы XZ;
- -Izip – сжимает архив с помощью программы Lzip;
- -Izma – сжимает архив с помощью программы Izma;
- -z, -gzip, -gunzip, -ungzip – сжимает архив с помощью программы GZIP;
- -Z, -compress, -uncompress – использование компрессии.
У команды tar есть еще много возможностей – чтобы их посмотреть, достаточно в консольном окне ввести команду tar —help. О том, как воспользоваться наиболее важными опциями и поработать с архивацией данных, мы поговорим в следующем разделе.
Как воспользоваться архиватором tar
Для работы с архиватором будем использовать сборку Kali Linux. Данный алгоритм подойдет и для других версий Unix/Linux, поэтому можете просто следовать инструкциям, чтобы прийти к тому же результату.
Создать новый архив или распаковать уже созданный мы можем двумя путями: воспользоваться необходимыми командами через консоль либо использовать встроенный архиватор ручным способом. Давайте рассмотрим оба варианта и посмотрим, как с их помощью можно создать новый архив, посмотреть его содержимое, распаковать данные и провести их сжатие.
Архивируем файлы
Чтобы добавить один или несколько файлов в архив через консольное окно, нам потребуется сначала прописать пути, чтобы система понимала, откуда брать файлы. Сделать это довольно просто: указываем в консоли путь до директории, в которой находятся файлы. В нашем случае это /home/kali/.
Для архивации вводим команду типа:
В результате будет создан архив в исходной папке – перейдем в нее и убедимся, что все прошло корректно:
Второй способ – ручное архивирование. Для этого выбираем файл, который нужно заархивировать, и кликаем по нему правой кнопкой мыши. В отобразившемся меню нажимаем на функцию создания архива. Далее нам потребуется указать название файла, задать ему расширение .tar и воспользоваться кнопкой архивирования файлов.
Как видите, создать tar-архив в Linux совсем не сложно. Если вам нужно заархивировать несколько документов через консоль, то просто пропишите их имена с использованием пробела.
Распаковываем tar-файлы
В данном случае нам также потребуется в консольном окне перейти в нужную директорию. Как только пути будут прописаны, можно вводить команду для разархивации:
Таким образом будут получены файлы, находящиеся в архиве. Также мы можем их достать и ручным способом – для этого достаточно кликнуть правой кнопкой мыши по файлу и нажать на «Извлечь здесь».
Как работать со сжатием файлов
Напоминаю, что tar не сжимает файлы, а только добавляет их в архив. Для уменьшения размера архивируемых файлов потребуется дополнительно воспользоваться такими утилитами, как bzip2 и gzip. Они хорошо взаимодействуют с tar, поэтому в консольном окне достаточно прописать несколько новых значений. В ручном режиме сжатие файлов выполняется с помощью расширения .tar.bz2 или .tar.gz.
Итак, для сжатия в bzip2 переходим через консоль в нужную директорию и прописываем следующую команду:
Чтобы использовать gzip, другую утилиту для сжатия, вводим следующее:
Для распаковки файлов такого типа используйте:
Ручной способ аналогичен созданию обычного архива, только необходимо указать расширение .tar.bz2 либо .tar.gz.
Распаковать файлы самостоятельно тоже просто – для этого нужно кликнуть правой кнопкой по архиву и выбрать «Извлечь здесь».
Как посмотреть содержимое архива
Мы можем посмотреть, что находится в архиве без его распаковки. В консоли для этого необходимо ввести команду такого типа:
Обратите внимание, что под командой отобразилось название «document1» – это файл, находящийся в архиве. Если файлов несколько, то каждый будет прописан в новой строке.
Для просмотра архива без использования консоли достаточно кликнуть двойным щелчком мыши по архиву. После этого отобразится новое окно, в котором будет показан весь список файлов.
Заключение
Сегодня мы рассмотрели основные методы архивации, распаковки и сжатия файлов с помощью команды tar. Это простой инструмент, который отлично взаимодействует с утилитами сжатия bzip2 и gzip. Надеюсь, что теперь вам будет легко работать с архивами в системе Linux. Спасибо за внимание!
Archiving and Compression on Linux: An Introduction
Exploring the tar utility and standard compression tools on Linux
Introduction
Archiving is the process of combining multiple files into a single package called an archive. This archive can then be easily distributed to another machine, backed up in a repository somewhere, or simply kept on your own machine as a way to organize and cleanup your file system. Archives are also an essential component of the Linux ecosystem, because all the software you install via your distribution’s package manager will initially be downloaded as a compressed archive from a remote repository. Therefore, working with archives is an important aspect of using a Linux based operating system effectively.
This article will introduce the standard archiving tool used on Linux — which is the tar software utility — and demonstrate its usage on the command line to create and work with archives, or tarballs. The tar utility is also able to compress an archive via a compression tool. This usage pattern of firstly creating an archive and then compressing it using a compression tool is often adopted for distributing packages remotely.
Compressing an archive can reduce its storage space requirements and is an important step in preparing it for distribution. With these points in mind, this article will also introduce the major compression tools on Linux, and discuss their usage both with tar and individually on the command line. More specifically, we shall take a look at the gzip, bzip2, xz and zstd compression tools.
The tar File Archiver
Tar was initially released in January 1979 and has since evolved into the standard file archiver on Linux. As of writing this article in November 2020, the latest stable version of tar was released on February 23, 2019 and therefore is still in active development to this day.
If tar is not on your system already, go ahead and install it via your Linux distribution’s package manager:
I won’t dive into the intricacies of how tar works under the hood too much in this article, but I will mention some important points to be aware of as we progress through the commands in subsequent sections.
Compression Tools
There are quite a few compression tools available on Linux, with each one implementing a specific compression algorithm. The compression tools introduced in this article all have a very similar command line interface and usage pattern, which means that if you know how to use one of the tools, you can use them all.
Go ahead and install the gzip, bzip2, xz and zstd compression tools via your Linux distribution’s package manager:
A later section in the article will describe each compression tool in more detail and present some useful command line options as well. For now, the upcoming table provides an overview of the four compression tools we just installed. Also take note of the Extension column since we will need to specify one of these file extensions in order to compress files with the associated compression tool via tar:
Why do we need to know about so many compression tools? Well, there are a few reasons. Even if package managers adopt a modern compression tool such as zstd or xz, there will still be a plethora of packages and repositories out there compressed with the older gzip or bzip2. In order to decompress and access the files in these archives, the associated compression tool is required. In addition, you may find that an older compression tool such as gzip or bzip2 is sufficient for your needs.
Environment Setup
This section will demonstrate a couple of simple command line tools that will enable us to identify a file’s type, as well as output a file or directory’s size in a human readable format. These tools might come in handy for inspecting the various archive formats we’ll be working with. I’ll also provide some instructions for setting up a working directory and how to acquire some wallpaper files for readers who wish to follow along with the article and use the same commands.
Feel free to skip this section if you want to go straight to the archiving and compression commands.
Determining the Type of a File
The file command outputs a file’s type and should already be installed on your Linux system. To invoke the tool, simply pass the name of a file you want to inspect, such as a JPEG image:
We can use the file command to confirm the type of archives, compressed files and regular files on the system. Feel free to use it if you ever get confused on what type of file you’re working with.
Determining the Size of Files and Directories
The du command (Disk Usage) outputs the disk space usage of files and directories on a system. Similar in syntax to the file tool, simply specify the files and directories you wish to know the size of:
By default, du outputs the size of files in kilobytes — 4516 and 3512 in the example above. The -h flag outputs the file size in a more human-readable format, while the -c flag displays the total size of the files as well:
File sizes are now displayed in megabytes and have an M appended to the output. The total size of the files is also displayed at the bottom of the list. In addition to files, directories can also be passed to du . Feel free to check out the manual pages and have a play with the tool before continuing.
Downloading Some Files to Work With
Let’s go ahead and set up a working directory for us to try out the archiving and compression commands demonstrated in the subsequent sections:
From here, copy over some wallpapers from your /usr/share/backgrounds/ directory. If you do not have any wallpapers on your system, feel free to download the gnome-backgrounds package, which provides some nice wallpapers for your desktop. This package will require about 40MB of space on your system:
Then copy the backgrounds into your working directory:
Now we have a place to work along with some files, let’s take a look at some tar commands in the next section.
An Archiving and Compression Tutorial
Now that we understand what a file archiver and a compression tool is, let’s take a look at some commands to solve a few real-world scenarios.
When working with tar on the command line, you will often use the same command line options for achieving a specific task — such as creating and extracting archives, as well as listing files within an archive. These frequently used options are detailed here:
The tar utility also provides several options that enable filtering archives through specific compression tools. For example, if you wish to compress an archive with gzip, we would pass the z option along with the aforementioned cf options. The following table lists the filtering options available to tar that we shall use in this tutorial:
There are many more filtering options available to tar on the command line, so feel free to explore the manual pages after reading this article.
Moving forward, let’s enter our working directory and create some archives of desktop wallpapers by executing these commands in the terminal:
The time it takes to create the compressed archive will differ depending on the filter passed to tar — this is because each filter implements a different compression algorithm. On my machine, the xz filter took the most time to compress the files, whilst the zstd filter performed the fastest.
Let’s list the files in the archives we’ve just created by using the -t option:
Tar needs to firstly decompress the archive before retrieving the file names. Notice that xz’s decompression algorithm performs much faster than its compression algorithm.
It is also possible to list the individual files and directories within an archive:
If you intend to extract an archive, It is good practice to firstly list the archive’s files before performing the actual extract operation. For example, if you mistakenly downloaded a huge archive and immediately extract all the files before checking it’s content, you could be in some trouble!
The Vim and Emacs text editors are also able to list the files contained in an archive. To list the files in one of our archives with Vim, run this command:
Vim’s syntax highlighting and search features might make life easier when browsing through an archive’s files.
Let’s clean up our working directory by placing all the archives we’ve created in a nested directory called example-01 :
Thus far, the parent gnome/ directory has been added to our archives. What if we want our archive to only include image files? The -C option solves this problem as it allows us to move into a directory before performing an operation with tar:
Files can also be deleted from an uncompressed .tar archive with the -delete option. Therefore, we must firstly decompress an archive before attempting to delete any of its content:
Notice that we had to use the bzip2 program on the command line to decompress the wallpapers.tar.bz2 archive. We then deleted the files and compressed it with bzip2 once again. Conversely, files are appended to an archive via the -r option:
To extract files from an archive we use tar’s -x option. If we extract a file into a directory with an identical file already there, that original file will be overwritten. It is therefore important to be aware of the location you plan to extract files to and the possibility of any files being overwritten. Let’s go ahead and extract one of the archives in our working directory:
All of our images were extracted in our working directory! This isn’t very clean — it would be useful if we could extract all the files into a separate folder. This is possible if we specify the one-top-level option:
Our extracted files were all written into the top directory. If you don’t assign a directory name to the —one-top-level option, files will be extracted into a directory with the same name as the archive:
To extract individual files and directories from the archive, simply append the items you’d like to extract to the end of the command:
We have built up enough knowledge to work with our own compressed archives in Linux. Let’s go ahead and clean up our working directory before moving onto the last example:
Lastly, we will look at how to append a tarball to another tarball using the -A option:
Notice that tar doesn’t allow you to append compressed archives. You will need to decompress the compressed archives you wish to combine before performing the actual append operation. After appending bar.tar to foo.tar in the above example, foo.tar is compressed with gzip, producing foo.tar.gz .
After compressing a file with gzip, the original uncompressed archive is discarded. Specify the -k option (keep) to keep the uncompressed version on the filesystem.
Lets wrap up the tutorial by cleaning up the working directory one more time:
Other Useful tar options
Feel free to experiment with some additional tar options presented in the following table:
I also encourage you to check out the tar manual pages, which will certainly be your best resource for finding new information about the tool:
A Closer Look at the Compression Tools
This section serves as a quick reference for readers wishing to familiarize themselves on the command line interface of our adopted compression tools.
Command Line Reference — gzip
Command Line Reference — bzip2
Command Line Reference — xz
Command Line Reference — zstd
In Conclusion
This article provided an introduction to working with archives on Linux using the tar file archiver and some standard Linux compression tools — including gzip, bzip2, xz and zstd. I hope the article has provided enough information and hands-on examples such that you can now comfortably create and manage your own archives on Linux.
From here, I encourage you to read further into the manual pages of tar and the various compression tools available on Linux, as well as looking into the pros and cons that come with using the individual compression algorithms.
Практические примеры использования tar
Oct 11, 2018 07:03 · 369 words · 2 minute read tar ubuntu debian centos
Для создания и манипуляций с архивами в 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 -[ОПЦИИ] имя_архива архивируемые_файлы . Рассмотрим несколько конкретных примеров.
- Создание несжатого архива (с расширением .tar ):
Примечание. Можно использовать абсолютные пути к файлам, вместо относительных, как в примере выше.
- Создание сжатого gzip-архива (с расширением .tgz ):
- Создание сжатого bzip2-архива (с расширением .bz2 ):
- Создание сжатого gzip-архива (с расширением .tgz ) без файлов с расширением jpg , gif , png , wmv , flv , tar , gz , zip :
- Создание архива без добавления абсолютного пути в метаданные (может быть полезно при извлечении данных из архива):
- Создание архива всех файлов в текущей директории, начинающихся на i :
- Добавление файла в существующий архив:
- Слияние содержимого двух архивов в один (добавляет содержимое fullbackup.tar в архив backup.tar ):
- Извлечение содержимого несжатого архива:
- Извлечение содержимого сжатого архива (формат .tgz ):
- Извлечение содержимого сжатого архива (формат .bz2 ):
- Извлечение содержимого несжатого архива в определенный каталог на диске:
- Извлечение конкретного файла из архива:
- Просмотр содержимого gzip-архива:
- Просмотр содержимого bzip2-архива:
- Сохранение символьных ссылок при создании архива (дополнительная опция -h ):
Консольная утилита tar — одна из наиболее часто используемых в мире Linux — будет полезна при создании резервных копий, установке пакетов, обмене файлами, шифровании и дешифровке данных.