- Использование tar в Linux и FreeBSD для работы с архивами
- Создание и распаковка архивов
- Создать
- Распаковать
- Примеры
- Распаковать в определенную папку
- Распаковка без вложенной папки
- Исключение файлов по маске
- Работа с архивами, разбитыми на части
- Описание ключей tar
- Команды для действия
- Дополнительные опции
- Windows
- 18 Tar Command Examples in Linux
- 1. Create tar Archive File in Linux
- 2. Create tar.gz Archive File in Linux
- 3. Create tar.bz2 Archive File in Linux
- 4. Untar tar Archive File in Linux
- 5. Uncompress tar.gz Archive File in Linux
- 6. Uncompress tar.bz2 Archive File in Linux
- 7. List Content of tar Archive File in Linux
- 8. List Content tar.gz Archive File in Linux
- 9. List Content tar.bz2 Archive File in Linux
- 10. Untar Single file from tar File in Linux
- 11. Untar Single file from tar.gz File in Linux
- 12. Untar Single file from tar.bz2 File in Linux
- 13. Untar Multiple files from tar, tar.gz, and tar.bz2 File
- 14. Extract Group of Files using Wildcard in Linux
- 15. Add Files or Directories to tar Archive File in Linux
- 16. Add Files or Directories to tar.gz and tar.bz2 Files
- 17. How To Verify tar, tar.gz, and tar.bz2 Archive File
- 18. Check the Size of the tar, tar.gz, and tar.bz2 Archive File
- Tar Usage and Options
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Использование tar в Linux и FreeBSD для работы с архивами
Утилита командной строки tar используется для работы с архивами в операционных системах на базе UNIX. С ее помощью можно архивировать данные и оптимизировать использование дискового пространства.
Создание и распаковка архивов
Создать
Создание выполняется с ключом c. Синтаксис следующий:
tar -czvf archive.tar.gz /home/dmosk
* в данном примере будет создан архив archive.tar.gz домашней директории пользователя (/home/dmosk)
** где z — сжать архив в gzip (без этого параметра, tar не сжимает, а создает так называемый тарбол); c — ключ на создание архива; v — verbose режим, то есть с выводом на экран процесса (очень удобно для наблюдением за ходом работы, но в скриптах можно упустить); f — использовать файл (обязательно указываем, так как в большей степени работаем именно с файлами).
Распаковать
Распаковка выполняется с ключом x с синтаксисом:
tar -xvf archive.tar.gz
Примеры
Распаковка .gz файла:
tar -xvf 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.
Распаковывается, как gzip:
tar -xvzf archive.tgz
Распаковать в определенную папку
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 пропустит одну вложенную папку внутри архива.
Исключение файлов по маске
Если необходимо пропустить некоторые файлы, вводим команду с ключом —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
Команды для действия
Ключ | Описание |
---|---|
-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 не работает с 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.
Источник
18 Tar Command Examples in Linux
The Linux “tar” stands for tape archive, which is used by a large number of Linux/Unix system administrators to deal with tape drives backup.
The tar command is used to rip a collection of files and directories into a highly compressed archive file commonly called tarball or tar, gzip and bzip in Linux.
The tar is the most widely used command to create compressed archive files and that can be moved easily from one disk to another disk or machine to machine.
Linux Tar Command Examples
In this article, we will be going to review and discuss various tar command examples including how to create archive files using (tar, tar.gz, and tar.bz2) compression, how to extract archive file, extract a single file, view content of the file, verify a file, add files or directories to the existing archive file, estimate the size of tar archive file, etc.
The main purpose of this guide is to provide various tar command examples that might be helpful for you to understand and become an expert in tar archive manipulation.
1. Create tar Archive File in Linux
The below example command will create a tar archive file tecmint-14-09-12.tar for a directory /home/tecmint in the current working directory. See the example command in action.
Let’s discuss each option used in the above command to create a tar archive file.
- c – Creates a new .tar archive file.
- v – Verbosely show the .tar file progress.
- f – File name type of the archive file.
2. Create tar.gz Archive File in Linux
To create a compressed gzip archive file we use the option as z. For example, the below command will create a compressed MyImages-14-09-12.tar.gz file for the directory /home/MyImages. (Note: tar.gz and tgz both are similar).
3. Create tar.bz2 Archive File in Linux
The bz2 feature compresses and creates an archive file less than the size of the gzip. The bz2 compression takes more time to compress and decompress files than gzip, which takes less time.
To create a highly compressed tar file we use the option j. The following example command will create a Phpfiles-org.tar.bz2 file for a directory /home/php. (Note: tar.bz2 and tbz is similar to tb2).
4. Untar tar Archive File in Linux
To untar or extract a tar file, just issue the following command using option x (extract). For example, the below command will untar the file public_html-14-09-12.tar in the present working directory.
If you want to untar in a different directory then use option as -C (specified directory).
5. Uncompress tar.gz Archive File in Linux
To Uncompress tar.gz archive file, just run the following command. If we would like to untar in different directories, just use option -C and the directory path, as shown in the above example.
6. Uncompress tar.bz2 Archive File in Linux
To Uncompress the highly compressed tar.bz2 file, just use the following command. The below example command will untar all the .flv files from the archive file.
7. List Content of tar Archive File in Linux
To list the contents of the tar archive file, just run the following command with option t (list content). The below command will list the content of the uploadprogress.tar file.
8. List Content tar.gz Archive File in Linux
Use the following command to list the content of the tar.gz file.
9. List Content tar.bz2 Archive File in Linux
To list the content of the tar.bz2 file, issue the following command.
10. Untar Single file from tar File in Linux
To extract a single file called cleanfiles.sh from cleanfiles.sh.tar use the following command.
11. Untar Single file from tar.gz File in Linux
To extract a single file tecmintbackup.xml from the tecmintbackup.tar.gz archive file, use the command as follows.
12. Untar Single file from tar.bz2 File in Linux
To extract a single file called index.php from the file Phpfiles-org.tar.bz2 use the following option.
13. Untar Multiple files from tar, tar.gz, and tar.bz2 File
To extract or untar multiple files from the tar, tar.gz, and tar.bz2 archive file. For example, the below command will extract “ file 1” “ file 2” from the archive files.
14. Extract Group of Files using Wildcard in Linux
To extract a group of files we use wildcard-based extracting. For example, to extract a group of all files whose pattern begins with .php from a tar, tar.gz, and tar.bz2 archive file.
15. Add Files or Directories to tar Archive File in Linux
To add files or directories to the existing tar archive files we use the option r (append). For example, we add file xyz.txt and directory php to the existing tecmint-14-09-12.tar archive file.
16. Add Files or Directories to tar.gz and tar.bz2 Files
The tar command doesn’t have an option to add files or directories to an existing compressed tar.gz and tar.bz2 archive file. If we do try will get the following error.
17. How To Verify tar, tar.gz, and tar.bz2 Archive File
To verify any tar or compressed archived file we use the option W (verify). To do this, just use the following examples of commands. (Note: You cannot do verification on a compressed ( *.tar.gz, *.tar.bz2 ) archive file).
18. Check the Size of the tar, tar.gz, and tar.bz2 Archive File
To check the size of any tar, tar.gz, and tar.bz2 archive file, use the following command. For example, the below command will display the size of the archive file in Kilobytes (KB).
Tar Usage and Options
- c – create an archive file.
- x – extract an archive file.
- v – show the progress of the archive file.
- f – filename of the archive file.
- t – viewing the content of the archive file.
- j – filter archive through bzip2.
- z – filter archive through gzip.
- r – append or update files or directories to the existing archive files.
- W – Verify an archive file.
- wildcards – Specify patterns in UNIX tar command.
That’s it for now, hope the above tar command examples are enough for you to learn, and for more information please use the man tar command.
If you are looking to split any large tar archive file into multiple parts or blocks, just go through this article:
If we’ve missed any examples please do share with us via the comment box and please don’t forget to share this article with your friends. This is the best way to say thanks…..
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.
Источник