Linux commands for tar

Команда 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

Создание архива tar

2. Просмотр содержимого архива

Следующая команда выводит содержимое архива, не распаковывая его:

Отображение архива

3. Распаковка архива tar Linux

Распаковывает архив test.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

Сжатие в bz2

Синтаксис для gzip отличается одной буквой в параметрах, и меняется окончание расширения архива:

tar -czvf archive.tar.gz file1 file2 file3

Сжатие в gz

При распаковке tar-архивов с таким расширением следует указывать соответствующую опцию:

Читайте также:  Linux повышение привилегий sudo

tar -C «Test» -xjvf arhive.tar.bz2

Распаковка bz2

Распаковка gz

На заметку: архиватор tar — одна из немногих утилит в GNU/Linux, в которой перед использованием однобуквенных параметров, стоящих вместе, можно не ставить знак дефиса.

Выводы

В этой статье была рассмотрена команда tar Linux, которая используется для архивации файлов и поставляется по умолчанию во всех дистрибутивах. В её возможности входит создание и распаковка архива файлов без их сжатия. Для сжатия утилита применяется в связке с популярными компрессорами bzip2 и gzip.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Linux tar command

Computer Hope

On Unix-like operating systems, the tar command creates, maintains, modifies, and extracts files that are archived in the tar format.

This page covers the GNU/Linux version of tar.

Description

«Tar» stands for tape archive. It is an archiving file format.

tar was originally developed in the early days of Unix for the purpose of backing up files to tape-based storage devices. It was later formalized as part of the POSIX standard, and today is used to collect, distribute, and archive files, while preserving file system attributes such as user and group permissions, access and modification dates, and directory structures.

This documentation covers the GNU version of tar, which is included with most modern variants of the Linux operating system.

Syntax

tar [-] A --catenate --concatenate | c --create | d --diff --compare | --delete | r --append | t --list | --test-label | u --update | x --extract --get [options] [pathname . ]

Operation

The first argument to tar should be a function specification: either one of the letters A, c, d, r, t, u, or x, or one of the long function names. A function letter does not need to be prefixed with a dash (««), and may be combined with other single-letter options. A long function name must be prefixed with a double dash (««). Some options take a parameter; with the single-letter form these must be given as separate arguments. With the long form, they may be given by appending «=value» to the option.

For example, the following commands are all equivalent:

tar --create --file=archive.tar file1 file2
tar -c -f archive.tar file1 file2
tar -cf archive.tar file1 file2
tar cf archive.tar file1 file2

Functions

Specifying one of the following functions selects what tar‘s main mode of operation will be:

A, —catenate,
—concatenate
Append tar files to an archive.
c, —create Create a new archive.
d, —diff, —compare Calculate any differences between the archive and the file system.
—delete Delete from the archive. (This function doesn’t work on magnetic tapes).
r, —append Append files to the end of a tar archive.
t, —list List the contents of an archive.
—test-label Test the archive label, and exit.
u, —update Append files, but only those that are newer than the copy in the archive.
x, —extract, —get Extract files from an archive.

Other options

The following options specify the way tar operates:

bell Play an audible bell at the console.
dot, . Print a single dot.
echo Display a text message at the console (to standard error).
echo=string Display string string on standard error; before output, any metacharacters in string are expanded.
exec=command Execute the given command.
sleep=time Wait for time seconds.
ttyout=string Output string on the current console (‘/dev/tty‘).
Читайте также:  Linux настройка автоматического входа

Several —checkpoint-action options can be specified. The supplied actions will be executed in the order of their appearance on the command line.

  • CVS/, and everything under it
  • RCS/, and everything under it
  • SCCS/, and everything under it
  • .git/, and everything under it
  • .gitignore
  • .cvsignore
  • .svn/, and everything under it
  • .arch-ids/, and everything under it
  • /, and everything under it
  • =RELEASE-ID
  • =meta-update
  • =update
  • .bzr
  • .bzrignore
  • .bzrtags
  • .hg
  • .hgignore
  • .hgrags
  • _darcs

PROG should follow two conventions: First, when invoked without additional options, it should read data from standard input, compress it and output it on standard output. Secondly, if invoked with the additional ‘-d‘ option, it should do exactly the opposite: read the compressed data from the standard input and produce uncompressed data on the standard output.

This option instructs tar to process only the numberth occurrence of each named file. The number defaults to 1, so:

tar -x -f archive.tar --occurrence filename

The —same-order option tells tar that the list of file names to be listed or extracted is sorted in the same order as the files in the archive. This allows a large list of names to be used, even on a small machine that would not otherwise be able to hold all the names in memory at the same time. Such a sorted list can easily be created by running tar -t on the archive and editing its output.

tar --extract --file archive.tar --strip-components=2
tar cf archive.tar --transform 's,^\./,usr/,'

Multiple «—warning» specifications may be used.

There are keywords for various warning messages available in tar. The two global keywords are:

Environment

The following environment variables affect the operation of tar:

SIMPLE_BACKUP_SUFFIX File name suffix to use when backing up files, if —suffix is not specified. The default backup suffix is «~«.
TAR_OPTIONS Any options specified in this variable will be prepended to options specified to tar on the command line.
TAPE The archiving tape or file to use if —file is not specified. If this variable is not defined, and no —file is specified, tar uses standard input and standard output instead.

Examples

tar -cf archive.tar file1 file2

Create archive archive.tar containing files file1 and file2. Here, the c tells tar you will be creating an archive; the f tells tar that the next option (here it’s archive.tar) will be the name of the archive it creates. file1 and file2, the final arguments, are the files to be archived.

List the files in the archive archive.tar verbosely. Here, the t tells tar to list the contents of an archive; v tells tar to operate verbosely; and f indicates that the next argument will be the name of the archive file to operate on.

Extract the files from archive archive.tar. x tells tar to extract files from an archive; f tells tar that the next argument will be the name of the archive to operate on.

Читайте также:  Debian gnu linux distribution

Extract the files from gzipped archive archive.tar.gz verbosely. Here, the z tells tar that the archive will be compressed with gzip.

Creates an archive of the directory mydir.

tar -czf archive.tar.gz mydir/

Creates an gzip-compressed archive of the directory mydir.

Extract the contents of the myfile.tar.gz into the current directory.

tar -xvf archive.tar documents/work/budget.doc

Extract only the file documents/work/budget.doc from the archive archive.tar. Produce verbose output.

tar -xvf archive.tar documents/work/

Extract only the directory documents/work/, and any files it contains, from the archive archive.tar. Produce verbose output.

tar -xvf archive.tar --wildcards '*.doc'

Extract only files with the extension .doc from the archive archive.tar. The —wildcards option tells tar to interpret wildcards in the name of the files to be extracted; the file name (*.doc) is enclosed in single-quotes to protect the wildcard (*) from being expanded incorrectly by the shell.

tar -rvf archive.tar documents/work/budget.doc

Add the file documents/work/budget.doc to the existing archive archive.tar. The r option is the same as the long option —append.

tar -uvf archive.tar documents/work/budget.doc

Add the file documents/work/budget.doc to the archive archive.tar only if it’s newer than the version already in the archive (or does not yet exist in the archive). Here, u is the same as the long option —update.

tar -cf - documents/work/ | wc -c

Estimate the file size of an archive of the directory documents/work, but do not create the file. Here, the archive file is specified as a dash (««), which tells tar to send its archived output to the standard output rather than a file on disk. This output is then piped to the wc command, which reports how many bytes (-c) were in the input it received.

tar -czf DogPhotos.tar.gz --exclude='kitty.jpg' MyPetPhotos

Create DogPhotos.tar.gz of all files contained in the MyPetPhotos without the kitty.jpg photo.

tar tf hope.tar.gz | grep myfile.txt

Search the hope.tar.gz file for the file myfile.txt and list the full path of the file. The returned results would resemble the line shown below.

tar -zxvf hope.tar.gz computerhopehope/homedir/public_html/data/myfile.txt

In the above example, the tar command would extract the one file myfile.txt from the hope.tar.gz. The full path to this file was determined using the example shown earlier.

ar — Create, modify, and extract files from archives.
basename — Strip directory information and suffixes from file names.
cd — Change the working directory.
chown — Change the ownership of files or directories.
cpio — Copy files to or from archives.
dirname — Strip the file name from a pathname, leaving only the directory component.
gzip —Create, modify, list the contents of, and extract files from GNU zip archives.
ls — List the contents of a directory or directories.
mt — Control magnetic tapes.
zcat — Print the uncompressed contents of compressed files.

Источник

Оцените статью
Adblock
detector