- Что такое тарболлы Linux и как их использовать?
- Каковы преимущества использования Tar-файла?
- Причины создания файлов Tar
- Недостаток использования файлов Tar
- Как создать файл Tar
- Как перечислить файлы в файле Tar
- Как извлечь файл Tar
- Tux Tweaks
- Linux Tweaks, HowTo’s and Reviews
- Command Line Basics: Create And Extract Tarballs
- Create a tarball
- Extract a tarball
- More information
- Getting Started With Tar Command
- Refresh the basics: Archive vs Compression
- Common tar files
- Tar command examples
- 1) Create a tarball
- 2) Create a gzip tarball
- Pay attention while using hyphen – with tar options
- 3) Create a bz2 tarball
- 4) List the contents of a tarball
- 5) Add more files to a tarball
- 6) Extract a tarball
- 7) Extract the tarball to a specific directory
- Summary
Что такое тарболлы Linux и как их использовать?
Согласно Википедии, тарбол – это компьютерный формат файла, который может объединять несколько файлов в один файл, называемый «тарбол», обычно сжатый.
Так как это помогает нам и для чего мы можем их использовать?
В прошлом tar-файлы создавались для хранения данных на лентах, а термин tar обозначает архивный архив на магнитной ленте. Хотя он все еще может использоваться для этой цели, концепция tar-файла – это просто способ сгруппировать множество файлов в один архив.
Каковы преимущества использования Tar-файла?
- Вы можете сгруппировать большое количество файлов в один файл tar
- Команда tar доступна в большинстве систем Linux, поэтому ее можно перемещать и извлекать без проблем совместимости.
- Файл tar поддерживает время доступа к файлам.
- Файл tar поддерживает права доступа к файлам.
- Файл tar содержит символические ссылки
- Вы можете записывать файлы tar на необработанные устройства, такие как лента, DVD, USB-накопители
Причины создания файлов Tar
Файлы tar при сжатии создают хорошие резервные копии и могут быть скопированы на DVD-диски, внешние жесткие диски, ленты и другие мультимедийные устройства, а также в сетевые папки. Используя файл tar для этой цели, вы можете извлечь все файлы из архива обратно в их исходные места, если вам нужно.
Файлы Tar также можно использовать для распространения программного обеспечения или другого совместно используемого контента. Приложение состоит из десятков различных программ и библиотек, а также другого вспомогательного контента, такого как изображения, файлы конфигурации, файлы readme и файлы make. Файл tar помогает сохранить эту структуру вместе для целей распространения.
Недостаток использования файлов Tar
В Википедии перечислены некоторые ограничения для использования файлов tar, которые включают, но не ограничиваются:
- Поддержка операционной системы. Файлы tar широко используются на платформах UNIX и Linux, но для их открытия в Windows требуются сторонние инструменты
- Tarbombs – в основном эти tar-файлы предназначены для расширения и размещения файлов в нескольких каталогах по всей вашей файловой системе. Это проблема при получении тарболов, а не при использовании ваших собственных. Как и большинство компьютерных технологий, ключом являются доверенные ресурсы.
- Труднее найти и извлечь отдельные файлы из файла tar
- При сжатии с помощью gzip вы должны распаковать весь файл, тогда как со стандартным файлом zip вы можете просматривать содержимое архива во время сжатия и извлекать отдельные файлы.
- Файл tar может содержать два одинаковых файла с одинаковым расположением, что может привести к перезаписи одного файла при извлечении.
Как создать файл Tar
Для создания файла tar вы используете следующий синтаксис:
tar -cf tarfiletocreate listoffiles
tar -cf garybackup ./Music/* ./Pictures/* ./Videos/*
Это создает tar-файл garybackup со всеми файлами в моей папке с музыкой, изображениями и видео. Полученный файл полностью распакован и занимает тот же размер, что и исходные папки.
Это не очень хорошо с точки зрения копирования по сети или записи на DVD, потому что это займет больше пропускной способности, больше дисков и будет медленнее копировать.
Вы можете использовать команду gzip вместе с командой tar для создания сжатого файла tar. По сути, сжатый tar-файл – это tarball.
Как перечислить файлы в файле Tar
Для получения списка содержимого файла tar используется следующий синтаксис:
tar -tvf имя_файла
tar -tvf garybackup
Как извлечь файл Tar
Чтобы извлечь все файлы из tar-файла, используйте следующий синтаксис:
Источник
Tux Tweaks
Linux Tweaks, HowTo’s and Reviews
Command Line Basics: Create And Extract Tarballs
In the Linux world, tarball refers to a compressed tar archive file. The most common type uses gzip compression and the file typically ends in tar.gz or .tgz. The tar command itself has its origin in Unix systems where is was used to save files to magnetic tape. The name tar stands for Tape ARchive.
The tarball is perhaps the most common way for program source code to be packaged for GNU/Linux systems. The tar file can be used to package several files together in a single archive. That archive file can then be compressed with one of several compression algorithms.
Create a tarball
To create a tarball, it’s good to have all of the files you want in the package to be contained in a directory. Although this is not necessary, it’s convenient when you then go to extract the file later. That way the archive will be extracted to its own directory rather than dumping its contents into the current directory. You can then create a tarball from the command line like this:
In the above command, tar is followed by four command parameters:
- c: create an archive
- v: verbose output (list the files that are being processed)
- z: compress the archive with gzip compression
- f: use a file archive instead of tape. The f parameter is immediately followed by the name of the archive file to create, that’s why it’s the last parameter used.
Extract a tarball
Extracting a tarball is done in a similar fashion to creating one. First you’ll want to place the tarball file in a directory where you would like to extract it. If you would like to inspect the contents of the archive before extracting it, you can do so with this command.
The t parameter is what tells tar to list the contents of the file.
Once you’ve got the archive placed in the directory you want it, you can extract it with:
In the above command, the x parameter is used to tell tar to extract the archive. The rest of the parameters have the same meaning as they had when creating an archive.
More information
There are many more advanced options available for working with tar. You can read the entire manual by viewing the tar manpage.
Источник
Getting Started With Tar Command
What is tar? Tar stands for “tape archive” and refers to a practice from the earlier days of computing when data was backed up to tapes. Despite the nostalgic origin of the name, tar is very powerful and uses modern technologies to archive and compress files.
Refresh the basics: Archive vs Compression
The tar command is important for Linux users to understand. Before we get too deep into the subject, let’s start things off with a little clarification.
- Archiving – The act of storing multiple files as one file.
- Compression – The act of shrinking a larger file or files.
Tar is an archiving tool. It creates a single file out of multiple files. This saves network bandwidth, time and processing power while transferring the files. A single file of 100 MB takes a lot less than transferring 100 files of 1 MB because of the file overhead.
This is why you’ll often find software available in a ‘tarball‘. Tarball is the common term used for a tar file.
While tar itself cannot compress files, you can use one of the common compression algorithms to compress the files while creating a tarball. I’ll show you how to do that later in this basic tar tutorial.
Common tar files
Here are some of the common “tar files” you’ll find:
.Tar: This is a tarball file. It is only an archive and no compression is performed.
.Tar.Gz or .tgz: This is the extension of an archive that has been compressed with Gzip.
.Tar.Bz2 or .tbz: This is the extension of an archive that has been compressed with Bz2. This is a relatively new technology. It features a higher ratio of compression, but that increased shrinking power means it takes a bit longer to complete.
.Tar.xz or .txz, etc.: Tar also features built in support for xz, lzip, and more. These tools primarily use the same compression algorithm, LZMA. The popular 7z that has become fairly common in Windows environments also uses this algorithm. Further differences in the files result from structure and metadata. I won’t go into these details in our examples, but I wanted to mention them.
It’s important to remember that extensions are not necessary on Linux and other Unix-based systems. Your Unix system can typically identify files by their headers regardless of extension, but using the common naming scheme can help avoid confusion. You may use the file command in Linux to know the type of a file.
Tar command examples
For this article, I want to demonstrate some of the common methods for archiving and compressing files using tar.
I have assembled some files of different types in my Documents folder. There are stock images and some text files. We will look at how the file size is changed by the compression through several examples.
Here is a complete list of the documents that will be used.
I’ve already touched on the capabilities of tar. It is a powerful tool with a lot of options. The various options and file types may make the command appear more complicated than it really is. As always, my goal is to demystify the command line. So let’s break things down into smaller pieces before combining several options in the examples.
Here is a table of commonly used options. Keep in mind, this is just the beginning. I recommend going through the help documentation yourself to find even more possibilities once you feel comfortable.
Switch | Expansive Options | Description |
---|---|---|
-c, | –create | create a new archive |
-d, | –diff, –compare | find differences between archive and file system |
-r, | –append | append files to the end of an archive |
-t, | –list | list the contents of an archive |
-u, | –update | only append files newer than copy in archive |
-x, | –extract, –get | extract files from an archive |
-j, | –bzip2 | filter the archive through bzip2 |
-z, | –gzip, –gunzip, –ungzip | filter the archive through gzip |
1) Create a tarball
Earlier I mentioned the common file types associated with the tar command. This is perhaps the most basic.
Compression will not be applied so the file will occupy at least as much space as the files in the documents folder.
tar cvf (create, verbose, file-archive): it creates a new tar file named doc.tar from all the files in
Do note that the tarball will have the same directory structure as your source directory of the tarball.
2) Create a gzip tarball
Let’s try gzip compression while creating the tarball.
tar cvzf (create, verbose, g-zip, file-archive): it creates a new tar file named doc.tar.gz from all the files in
/Documents. It uses gzip compression (with option z) while creating the tarball.
As you can see, the gzipped tarball size is 54862 bytes (53MB) less that a normal, uncompressed tar ball.
Pay attention while using hyphen – with tar options
Usually, when you use options with a Linux command, you add hyphen (-) before the options.
The hyphen before options is not mandatory and is best avoided. This is why I haven’t used it in the examples.
If you use hyphen before the options, you should always keep the f at the end of the options. If you use tar -cvfz, the z becomes an argument for option z. And then you’ll see an error like this:
tar: doc.tar.gz: Cannot stat: No such file or directory
This is why it is a good practice to use the option f at the end of all other options so that even if you use hyphen out of habit, it won’t create a problem.
3) Create a bz2 tarball
Say, you want to create a bz2 tarball. The steps are same as the previous one. You just need to change the option z (gzip) to j (bz2). Refer to the option table I had mentioned earlier.
tar cvfj (create, verbose, bz2 type, file-archive).
Notice the size? It is even less than the gzipped tarball.
4) List the contents of a tarball
You can use the -t option (instead of -c) to view the contents of an archive file. This works the same whether the file is compressed or not. It will list the actual file size, not the compressed size.
5) Add more files to a tarball
You can append files to a tarball archive using -r . You cannot add files to a compressed archive without extracting them first using the tar command.
You can also append using the -u option for update. This option is supposed to only add the new files according to help docs, but in my practice, it worked the same as append, adding new copies of all the files.
6) Extract a tarball
Now that you have seen how the different types of compression affect the overall file size, let’s look at extracting those files.
I changed into a new directory called docs. Then I used tar xvf (extract, verbose, file-archive) to unpack the contents here.
It’s important to note that tar retains file structure so when I extract the files, they are in /home/christopher/Documents. To avoid this, you can switch to the desired directory (
/Documents) and copy all files using the * wildcard instead of the directory structure.
7) Extract the tarball to a specific directory
By default, the content of a tarball are extracted in the current directory. That’s not always desirable.
You can extract a tarball to a specific directory in the following manner:
The destination directory must exist so make sure to use mkdir command to create one beforehand.
Summary
Here’s what you need to keep in mind while using tar in Linux:
It is almost always used in tar cf or tar xvf format. Remember this:
- c stands for create: You use it for creating a tarball
- x stands for extract: You use it for extracting a tarball
- f stands for file: You use it for tar file name (for both creating or extracting). Try to use it at the end of the options.
- v stands for verbose: It’s optional but it shows what’s happening with the command.
Of course, you cannot use both c and x options in the same tar command.
Conclusion
Did you enjoy our guide to the tar command? I hope all of these tips taught you something new.
If you like this guide, please share it on social media. If you have any comments or questions, leave them below.
If you have any suggestions for topics you’d like to see covered, feel free to leave those as well. Thanks for reading.
Источник