Архив tar gz. Использование tar в Linux и FreeBSD для работы с архивами

Архиватор tar - наиболее распространенный архиватор, используемый в Linux-системах.

Я для вас (и себе на памятку) решил на русском языке привести основные, наиболее ходовые применимые в "быту" примеры создания и распаковки архивов, постаравшись разжевать для простыми и подробными пояснения, что да как. А также постарался частично перевести на русский язык использование некоторых опций. Казалось бы, что тут сложного с этими архивами, уж что, что, а это плевое дело. Но жизнь подсказывает, что нет нет, а постоянно мы обращаемся к мануалам, ищем в сети готовые решения, подсказки и даже не смотря на все то, что мы неоднократно ранее уже все это повторяли и проходили. Но на практике все просто, слишком у нас много иных забот, чтобы в голове держать все то, что мы когда либо в жизни делали, верно? Ну для чего нам тогда всякие книги, заметки и блокноты? То то! :)

Итак. Здесь на пожарный официальный мануал GNU tar:
https://www.gnu.org/software/tar/manual/tar.txt

На всякий пожарный мануал Tar для FreeBSD
freebsd.org tar manual

В самом низу статьи еще один мануал, более краткий, выдернутый из Debian 9.

Ну а мы переходим к насущному..

Используемые параметры (ключи, опции) tar

Можно использовать любые ключи, как короткие, так и длинные, то есть из первого столбца или из второго. Некоторые ключи не существуют в коротком виде, в таком случае необходимо использовать только длинные ключи.

-A

Catenate,
--concatenate

Присоединение tar-файлов к архиву.
-b Использовать 512 байт записи в I/O блоках.
-c --create Создать архив.
-C --directory=DIR Указать место назначения для извлечения содержания указанного архива. Измените DIR перед выполнением каких-либо операций. Эта опция чувствительна к порядку, т. е. она влияет на все последующие опции.
-d --diff,
--compare
Операция сравнения архива с заданной файловой системой.
--delete Удалить из архива. Аргументы содержат имена элементов архива, которые необходимо удалить. Как минимум нужно дать один аргумент. Этот параметр не работает с сжатыми архивами. Не существует короткий эквивалент ключа.
-f --file=ARCHIVE Создать файл (в противном случае выход идет к терминалу). Измените ARCHIVE перед выполнением каких-либо операций.
-g --listed-incremental=FILE Инкрементный режим архивированаия. Новый GNU формат.
-G --incremental Инкрементный режим архивированаия. Старый GNU формат. При использовании с параметром "-create", создается инкрементальный архив без создания моментального снимка. Таким образом, невозможно создать несколько уровней инкрементных резервных копий с опцией "--incremental".
--ignore-failed-read Не завершать работу, если некоторые файлы не удалось прочитать. Этот параметр действует только во время создания. Предупреждения об ошибках могут быть подавлены опцией "--warning=failed-read".
-j Использовать сжатие bzip2.
-J Использовать сжатие xz.
-k Не перезаписывать существующие файлы.
-lzma Использовать сжатие lzma.
-m --touch Не восстанавливать время модификации (только в режиме x). При создании архива время модификации всегда сохраняется.
-O Записать записи entries на stdout (не восстановит диск).
-p --preserve-permissions,
--same-permissions
Восстанавливать права доступа к файлам (только в режиме x). Попытка восстановить
полные разрешения, включая владельца, режимы файлов, списки ACL, расширенные
атрибуты и расширенные флаги файлов, если они доступны, для каждого элемента
извлеченного из архива (игнорирует маску). Этот параметр заставляет «tar» устанавливать режимы (разрешения доступа) на извлеченные файлы точно так же, как было записано в архиве. Если этот параметр не используется, текущая установка «umask» ограничивает разрешения на извлеченные файлы. Этот параметр по умолчанию включен, когда «tar» выполняется суперпользователем.
Этот параметр не имеет смысла с "-list" ("-t").
-P --absolute-names Сохранить имена путей. При создании архивов не удаляются ведущие косые черты из имен файлов. По умолчанию абсолютные имена путей (имена, начинающиеся с символа/) удаляют основную косую черту как при создании архивов, так и при извлечении из них. Кроме того, Tar откажется распаковывать архивные файлы, чьи имена содержат ".." или чей целевой каталог будет изменен с помощью символической ссылки. Этот параметр отключает такое поведение. Обычно при создании архива "tar" удаляет начальный символ "/" из имен членов, а также при извлечении из архива "tar" имена, если у них есть начальный символ "/" или внутренний "..". Эта опция отключает это поведение.
-r --append Добавление файла в архив.
tar -rf archive.tar add.txt
--strip-components=NUMBER Удаляет N ведущих компонентов из имен файлов при извлечении.
-S --sparse Если файл окажется разреженным, он будет специально обработан, что позволит уменьшить объем будущего архива. Этот параметр имеет смысл только при создании или обновлении архивов. Это не влияет на извлечение. Однако имейте в виду, что опция "-sparse" может представлять серьезный недостаток. Чтобы определить содержание файла, возможно, придется прочитать его перед попыткой архивирования, поэтому в целом файл может быть прочитан дважды. Такое поведение зависит от вашей ОС или файловой системы, которая не поддерживает функцию "SEEK_HOLE/SEEK_DATA". Тем не менее, рекомендуется использовать "-- sparse " при выполнении резервного копирования файловой системы, чтобы избегать архивирования развернутых форм файлов, хранящихся в системе. Вы можете быть уверены, что архив никогда не будет занимать больше места на носителе, чем файлы на диске.
-t Получить оглавление (содержание) из архива (вывести список файлов).
-u --update Добавить в архив файлы, которые являются более новыми, чем соответствующая копия в архиве. Аргументы имеют то же значение, что и с параметрами -c и -r.
-v --verbose Вывод списка упакованных файлов в процессе работы.
-w Интерактивный режим.
-W Опция служит для проверки архива.
-x --extract,
--get
Извлечение файлов.
-z --gzip,
--gunzip,
--ungzip
Использовать сжатие gzip.

Создать архив tar.gz

# Задача: Создать архив tar.gz с сжатием gzip. # # Переходить в нужный каталог не обязательно, команду можно выполнить из любого места. # # 1. Указываем ключи -czf. # 2. Указываем полный путь и название нового архива. # 3. Указываем полный путь к директории источнику. # # В результате, в директории /archives создастся архив new.tar.gz с содержимым # каталога /home/documents. tar -czf /archives/new.tar.gz /home/documents

Создать бекап tar.gz с сохранением путей и прав доступа

# Задача: Создать бекап tar.gz с сжатием gzip. # # Переходить в нужный каталог не обязательно, команду можно выполнить из любого места. # # 1. Указываем ключи -cPzf. # 2. Указываем полный путь и название нового архива. # 3. Указываем полный путь к директории источнику. # # В результате, в директории /archives создастся архив new.tar.gz с содержимым # каталога /home/user/site. tar -cPzf /backups/new.tar.gz /home/user/site

Распаковать архив tar.gz в текущую директорию

# Задача: Распаковать архив tar.gz в текущую директорию. # # 1. Переходим в нужный каталог. # 2. Указываем ключи -xzf. # 3. Указываем полный путь к архиву источнику. # # В результате выполнения, содержимое архива archive.tar.gz распакуется в директории, # в которой мы сейчас находимся, в данном случае это будет в /home/here. # Переходим в нужный каталог cd /home/here # Распаковываем в текущий каталог содержимое, указав полный путь к архиву источнику. tar -xzf /pub/downloads/archive.tar.gz


Распаковать архив tar.gz в указанную директорию

# Задача: Распаковать архив tar.gz в указанную директорию. # # Переходить в нужный каталог не обязательно, команду можно выполнить из любого места. # # 1. Указываем ключи -xzf. # 2. Указываем полный путь к архиву источнику. # 3. Указываем полный путь места назначения с помощью ключа -C. # # В результате выполнения, содержимое архива archive.tar.gz распакуется в # указанный каталог, в данном случае в директорию /home/here. tar -xzf /pub/downloads/archive.tar.gz -C /home/here


Распаковать содержимое архива tar.gz в текущую директорию с сохранением прав доступа

# Задача: Восстановить содержимое архива с сохранением/восстановлением прав доступа. # # Чтобы распаковать содержимое архива в таком режиме, добавляем ключ -p. # # 1. Переходим в нужный каталог. # 2. Указываем ключи -xzpf. # 3. Указываем полный путь к архиву источнику. # # В результате выполнения команды, содержимое архива backup.tar.gz распакуется с # восстановленными правами доступа, которые ранее были на момент архивации файлов. # Содержимое архива archive.tar.gz распакуется в директории, в которой мы сейчас # находимся, в данном случае это будет в /home/here. # Переходим в нужный каталог cd /home/here # Распаковываем в текущий каталог содержимое, указав полный путь к архиву источнику. tar -xzpf /pub/downloads/backup.tar.gz


Распаковать содержимое архива tar.gz в указанную директорию с сохранением прав доступа

# Задача: Восстановить содержимое архива с сохранением/восстановлением прав доступа. # # Чтобы распаковать содержимое архива в таком режиме, добавляем ключ -p. # # 1. Указываем ключи -xzpf. # 2. Указываем полный путь к архиву источнику. # 3. Указываем полный путь места назначения с помощью ключа -C. # # В результате выполнения команды, содержимое архива backup.tar.gz распакуется с # восстановленными правами доступа, которые ранее были на момент архивации файлов. # Содержимое архива archive.tar.gz распакуется в указанный каталог, в данном случае # в директорию /home/here. tar -xzpf /pub/downloads/backup.tar.gz -C /home/here


Восстановить содержимое архива tar.gz с сохранением путей и прав доступа

# Задача: Восстановить содержимое архива с сохранением путей и прав доступа. # Этот способ идеальное средство для бекапа и восстановления файлов. # Данный режим не инкрементный, но поддерживается также не только Linux, но # и в FreeBSD. Примечание: в FreeBSD не поддерживается инкрементный режим. # # Чтобы распаковать содержимое архива с сохранение путей и прав доступа, добавляем # ключ -p для восстановления прав доступа, а также ключ -P для восстановления иерархии # каталогов от корня. Данный ключ не удаляет ведущие косые черты из имен элементов. # # 1. Указываем ключи -xPzpf. # 2. Указываем полный путь к архиву источнику. # # В результате выполнения команды, содержимое из архива backup.tar.gz распакуется в том виде и # структуре с восстановленными правами доступа, которые ранее были на момент # архивации. По мере восстановления файлов, иерархия каталогов (в случае отсутствия) будет # воссоздана с нуля от самой корневой директории. Совпадающие на пути файлы будут # заменены/восстановлены, существующие иные файлы не будут затронуты. # # Примечание: в данном режиме с ключем -P нельзя одновременно использовать ключ -C, то есть # нельзя указать каталог назначения. Это просто не сработает, все равно будет восстановлена # исходная структура каталогов и файлов. Если хотите указать свой каталог для восстановления, # просто удалите опцию -P из запроса. tar -xPzpf /pub/downloads/backup.tar.gz


Распаковать архив в указанный каталог с сохранением прав доступа, но откинув например три начальные директории (Извлечь отдельную ветку каталогов)

# Задача: Извлечь отдельную ветку каталогов. # # Чтобы распаковать часть иерархии архива (с сохранение прав доступа также добавлен ключ -p), # мы будем использовать новую дополнительную опцию "--strip-components=NUMBER", где значение # NUMBER, это количество отброшенных (слева) начальных элементов. # # В архиве /archives/sitebk.2017.09.07.tar.gz: # /usr/home/user/virtual/site # Из архива будет извлечено в директорию /home/here: # virtual/site # tar -xzpf /usr/sitebk.2017.09.07.tar.gz --strip-components=3 -C /home/here

Добавить файл в архив tar

# Добвляем к архиву archive.tar файл add.txt. # Не забываем про ключ -P, если нужно. tar -rf archive.tar add.txt

Оригинальный MAN GNU tar Debian

TAR(1) GNU TAR Manual TAR(1) NAME tar - an archiving utility SYNOPSIS Traditional usage tar {A|c|d|r|t|u|x} UNIX-style usage tar -A ARCHIVE ARCHIVE tar -c [-f ARCHIVE] tar -d [-f ARCHIVE] tar -t [-f ARCHIVE] tar -r [-f ARCHIVE] tar -u [-f ARCHIVE] tar -x [-f ARCHIVE] GNU-style usage tar {--catenate|--concatenate} ARCHIVE ARCHIVE tar --create [--file ARCHIVE] tar {--diff|--compare} [--file ARCHIVE] tar --delete [--file ARCHIVE] tar --append [-f ARCHIVE] tar --list [-f ARCHIVE] tar --test-label [--file ARCHIVE] tar --update [--file ARCHIVE] tar --update [-f ARCHIVE] tar {--extract|--get} [-f ARCHIVE] NOTE This manpage is a short description of GNU tar. For a detailed discussion, including examples and usage rec‐ ommendations, refer to the GNU Tar Manual available in texinfo format. If the info reader and the tar docu‐ mentation are properly installed on your system, the command info tar should give you access to the complete manual. You can also view the manual using the info mode in emacs(1), or find it in various formats online at http://www.gnu.org/software/tar/manual If any discrepancies occur between this manpage and the GNU Tar Manual, the later shall be considered the authoritative source. DESCRIPTION GNU tar is an archiving program designed to store multiple files in a single file (an archive), and to manip‐ ulate such archives. The archive can be either a regular file or a device (e.g. a tape drive, hence the name of the program, which stands for tape archiver), which can be located either on the local or on a remote machine. Option styles Options to GNU tar can be given in three different styles. In traditional style, the first argument is a cluster of option letters and all subsequent arguments supply arguments to those options that require them. The arguments are read in the same order as the option letters. Any command line words that remain after all options has been processed are treated as non-optional arguments: file or archive member names. For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /etc into the archive file etc.tar verbosely listing the files being archived: tar cfv a.tar /etc In UNIX or short-option style, each option letter is prefixed with a single dash, as in other command line utilities. If an option takes argument, the argument follows it, either as a separate command line word, or immediately following the option. However, if the option takes an optional argument, the argument must fol‐ low the option letter without any intervening whitespace, as in -g/tmp/snar.db. Any number of options not taking arguments can be clustered together after a single dash, e.g. -vkp. Options that take arguments (whether mandatory or optional), can appear at the end of such a cluster, e.g. -vkpf a.tar. The example command above written in the short-option style could look like: tar -cvf a.tar /etc or tar -c -v -f a.tar /etc The options in all three styles can be intermixed, although doing so with old options is not encouraged. Operation mode The options listed in the table below tell GNU tar what operation it is to perform. Exactly one of them must be given. Meaning of non-optional arguments depends on the operation mode requested. -A, --catenate, --concatenate Append archive to the end of another archive. The arguments are treated as the names of archives to append. All archives must be of the same format as the archive they are appended to, otherwise the resulting archive might be unusable with non-GNU implementations of tar. Notice also that when more than one archive is given, the members from archives other than the first one will be accessible in the resulting archive only if using the -i (--ignore-zeros) option. Compressed archives cannot be concatenated. -c, --create Create a new archive. Arguments supply the names of the files to be archived. Directories are archived recursively, unless the --no-recursion option is given. -d, --diff, --compare Find differences between archive and file system. The arguments are optional and specify archive mem‐ bers to compare. If not given, the current working directory is assumed. --delete Delete from the archive. The arguments supply names of the archive members to be removed. At least one argument must be given. This option does not operate on compressed archives. There is no short option equivalent. -r, --append Append files to the end of an archive. Arguments have the same meaning as for -c (--create). -t, --list List the contents of an archive. Arguments are optional. When given, they specify the names of the members to list. --test-label Test the archive volume label and exit. When used without arguments, it prints the volume label (if any) and exits with status 0. When one or more command line arguments are given. tar compares the volume label with each argument. It exits with code 0 if a match is found, and with code 1 otherwise. No output is displayed, unless used together with the -v (--verbose) option. There is no short option equivalent for this option. -u, --update Append files which are newer than the corresponding copy in the archive. Arguments have the same meaning as with -c and -r options. -x, --extract, --get Extract files from an archive. Arguments are optional. When given, they specify names of the archive members to be extracted. --show-defaults Show built-in defaults for various tar options and exit. No arguments are allowed. -?, --help Display a short option summary and exit. No arguments allowed. --usage Display a list of available options and exit. No arguments allowed. --version Print program version and copyright information and exit. OPTIONS Operation modifiers --check-device Check device numbers when creating incremental archives (default). -g, --listed-incremental=FILE Handle new GNU-format incremental backups. FILE is the name of a snapshot file, where tar stores additional information which is used to decide which files changed since the previous incremental dump and, consequently, must be dumped again. If FILE does not exist when creating an archive, it will be created and all files will be added to the resulting archive (the level 0 dump). To create incremen‐ tal archives of non-zero level N, create a copy of the snapshot file created during the level N-1, and use it as FILE. When listing or extracting, the actual contents of FILE is not inspected, it is needed only due to syntactical requirements. It is therefore common practice to use /dev/null in its place. --hole-detection=METHOD Use METHOD to detect holes in sparse files. This option implies --sparse. Valid values for METHOD are seek and raw. Default is seek with fallback to raw when not applicable. -G, --incremental Handle old GNU-format incremental backups. --ignore-failed-read Do not exit with nonzero on unreadable files. --level=NUMBER Set dump level for created listed-incremental archive. Currently only --level=0 is meaningful: it instructs tar to truncate the snapshot file before dumping, thereby forcing a level 0 dump. -n, --seek Assume the archive is seekable. Normally tar determines automatically whether the archive can be seeked or not. This option is intended for use in cases when such recognition fails. It takes effect only if the archive is open for reading (e.g. with --list or --extract options). --no-check-device Do not check device numbers when creating incremental archives. --no-seek Assume the archive is not seekable. --occurrence[=N] Process only the Nth occurrence of each file in the archive. This option is valid only when used with one of the following subcommands: --delete, --diff, --extract or --list and when a list of files is given either on the command line or via the -T option. The default N is 1. --restrict Disable the use of some potentially harmful options. --sparse-version=MAJOR[.MINOR] Set version of the sparse format to use (implies --sparse). This option implies --sparse. Valid argument values are 0.0, 0.1, and 1.0. For a detailed discussion of sparse formats, refer to the GNU Tar Manual, appendix D, "Sparse Formats". Using info reader, it can be accessed running the following command: info tar "Sparse Formats". -S, --sparse Handle sparse files efficiently. Some files in the file system may have segments which were actually never written (quite often these are database files created by such systems as DBM). When given this option, tar attempts to determine if the file is sparse prior to archiving it, and if so, to reduce the resulting archive size by not dumping empty parts of the file. Overwrite control These options control tar actions when extracting a file over an existing copy on disk. -k, --keep-old-files Don"t replace existing files when extracting. --keep-newer-files Don"t replace existing files that are newer than their archive copies. --no-overwrite-dir Preserve metadata of existing directories. --one-top-level[=DIR] Extract all files into DIR, or, if used without argument, into a subdirectory named by the base name of the archive (minus standard compression suffixes recognizable by --auto-compress). --overwrite Overwrite existing files when extracting. --overwrite-dir Overwrite metadata of existing directories when extracting (default). --recursive-unlink Recursively remove all files in the directory prior to extracting it. --remove-files Remove files from disk after adding them to the archive. --skip-old-files Don"t replace existing files when extracting, silently skip over them. -U, --unlink-first Remove each file prior to extracting over it. -W, --verify Verify the archive after writing it. Output stream selection --ignore-command-error Ignore subprocess exit codes. --no-ignore-command-error Treat non-zero exit codes of children as error (default). -O, --to-stdout Extract files to standard output. --to-command=COMMAND Pipe extracted files to COMMAND. The argument is the pathname of an external program, optionally with command line arguments. The program will be invoked and the contents of the file being extracted sup‐ plied to it on its standard output. Additional data will be supplied via the following environment variables: TAR_FILETYPE Type of the file. It is a single letter with the following meaning: f Regular file d Directory l Symbolic link h Hard link b Block device c Character device Currently only regular files are supported. TAR_MODE File mode, an octal number. TAR_FILENAME The name of the file. TAR_REALNAME Name of the file as stored in the archive. TAR_UNAME Name of the file owner. TAR_GNAME Name of the file owner group. TAR_ATIME Time of last access. It is a decimal number, representing seconds since the Epoch. If the ar‐ chive provides times with nanosecond precision, the nanoseconds are appended to the timestamp after a decimal point. TAR_MTIME Time of last modification. TAR_CTIME Time of last status change. TAR_SIZE Size of the file. TAR_UID UID of the file owner. TAR_GID GID of the file owner. Additionally, the following variables contain information about tar operation mode and the archive being processed: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. Handling of file attributes --atime-preserve[=METHOD] Preserve access times on dumped files, either by restoring the times after reading (METHOD=replace, this is the default) or by not setting the times in the first place (METHOD=system) --delay-directory-restore Delay setting modification times and permissions of extracted directories until the end of extraction. Use this option when extracting from an archive which has unusual member ordering. --group=NAME[:GID] Force NAME as group for added files. If GID is not supplied, NAME can be either a user name or numeric GID. In this case the missing part (GID or name) will be inferred from the current host"s group database. When used with --group-map=FILE, affects only those files whose owner group is not listed in FILE. --group-map=FILE Read group translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single group. It must consist of two fields, delimited by any amount of whitespace: OLDGRP NEWGRP[:NEWGID] OLDGRP is either a valid group name or a GID prefixed with +. Unless NEWGID is supplied, NEWGRP must also be either a valid group name or a +GID. Otherwise, both NEWGRP and NEWGID need not be listed in the system group database. As a result, each input file with owner group OLDGRP will be stored in archive with owner group NEWGRP and GID NEWGID. --mode=CHANGES Force symbolic mode CHANGES for added files. --mtime=DATE-OR-FILE Set mtime for added files. DATE-OR-FILE is either a date/time in almost arbitrary format, or the name of an existing file. In the latter case the mtime of that file will be used. -m, --touch Don"t extract file modified time. --no-delay-directory-restore Cancel the effect of the prior --delay-directory-restore option. --no-same-owner Extract files as yourself (default for ordinary users). --no-same-permissions Apply the user"s umask when extracting permissions from the archive (default for ordinary users). --numeric-owner Always use numbers for user/group names. --owner=NAME[:UID] Force NAME as owner for added files. If UID is not supplied, NAME can be either a user name or numeric UID. In this case the missing part (UID or name) will be inferred from the current host"s user database. When used with --owner-map=FILE, affects only those files whose owner is not listed in FILE. --owner-map=FILE Read owner translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single UID. It must consist of two fields, delimited by any amount of whitespace: OLDUSR NEWUSR[:NEWUID] OLDUSR is either a valid user name or a UID prefixed with +. Unless NEWUID is supplied, NEWUSR must also be either a valid user name or a +UID. Otherwise, both NEWUSR and NEWUID need not be listed in the system user database. As a result, each input file owned by OLDUSR will be stored in archive with owner name NEWUSR and UID NEWUID. -p, --preserve-permissions, --same-permissions extract information about file permissions (default for superuser) --preserve Same as both -p and -s. --same-owner Try extracting files with the same ownership as exists in the archive (default for superuser). -s, --preserve-order, --same-order Sort names to extract to match archive --sort=ORDER When creating an archive, sort directory entries according to ORDER, which is one of none, name, or inode. The default is --sort=none, which stores archive members in the same order as returned by the operat‐ ing system. Using --sort=name ensures the member ordering in the created archive is uniform and reproducible. Using --sort=inode reduces the number of disk seeks made when creating the archive and thus can con‐ siderably speed up archivation. This sorting order is supported only if the underlying system pro‐ vides the necessary information. Extended file attributes --acls Enable POSIX ACLs support. --no-acls Disable POSIX ACLs support. --selinux Enable SELinux context support. --no-selinux Disable SELinux context support. --xattrs Enable extended attributes support. --no-xattrs Disable extended attributes support. --xattrs-exclude=PATTERN Specify the exclude pattern for xattr keys. PATTERN is a POSIX regular expression, e.g. --xat‐ trs-exclude="^user.", to exclude attributes from the user namespace. --xattrs-include=PATTERN Specify the include pattern for xattr keys. PATTERN is a POSIX regular expression. Device selection and switching -f, --file=ARCHIVE Use archive file or device ARCHIVE. If this option is not given, tar will first examine the environ‐ ment variable `TAPE". If it is set, its value will be used as the archive name. Otherwise, tar will assume the compiled-in default. The default value can be inspected either using the --show-defaults option, or at the end of the tar --help output. An archive name that has a colon in it specifies a file or device on a remote machine. The part before the colon is taken as the machine name or IP address, and the part after it as the file or device pathname, e.g.: --file=remotehost:/dev/sr0 An optional username can be prefixed to the hostname, placing a @ sign between them. By default, the remote host is accessed via the rsh(1) command. Nowadays it is common to use ssh(1) instead. You can do so by giving the following command line option: --rsh-command=/usr/bin/ssh The remote machine should have the rmt(8) command installed. If its pathname does not match tar"s default, you can inform tar about the correct pathname using the --rmt-command option. --force-local Archive file is local even if it has a colon. -F, --info-script=COMMAND, --new-volume-script=COMMAND Run COMMAND at the end of each tape (implies -M). The command can include arguments. When started, it will inherit tar"s environment plus the following variables: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. TAR_FD File descriptor which can be used to communicate the new volume name to tar. If the info script fails, tar exits; otherwise, it begins writing the next volume. -L, --tape-length=N Change tape after writing Nx1024 bytes. If N is followed by a size suffix (see the subsection Size suffixes below), the suffix specifies the multiplicative factor to be used instead of 1024. This option implies -M. -M, --multi-volume Create/list/extract multi-volume archive. --rmt-command=COMMAND Use COMMAND instead of rmt when accessing remote archives. See the description of the -f option, above. --rsh-command=COMMAND Use COMMAND instead of rsh when accessing remote archives. See the description of the -f option, above. --volno-file=FILE When this option is used in conjunction with --multi-volume, tar will keep track of which volume of a multi-volume archive it is working in FILE. Device blocking -b, --blocking-factor=BLOCKS Set record size to BLOCKSx512 bytes. -B, --read-full-records When listing or extracting, accept incomplete input records after end-of-file marker. -i, --ignore-zeros Ignore zeroed blocks in archive. Normally two consecutive 512-blocks filled with zeroes mean EOF and tar stops reading after encountering them. This option instructs it to read further and is useful when reading archives created with the -A option. --record-size=NUMBER Set record size. NUMBER is the number of bytes per record. It must be multiple of 512. It can can be suffixed with a size suffix, e.g. --record-size=10K, for 10 Kilobytes. See the subsection Size suffixes, for a list of valid suffixes. Archive format selection -H, --format=FORMAT Create archive of the given format. Valid formats are: gnu GNU tar 1.13.x format oldgnu GNU format as per tar <= 1.12. pax, posix POSIX 1003.1-2001 (pax) format. ustar POSIX 1003.1-1988 (ustar) format. v7 Old V7 tar format. --old-archive, --portability Same as --format=v7. --pax-option=keyword[[:]=value][,keyword[[:]=value]]... Control pax keywords when creating PAX archives (-H pax). This option is equivalent to the -o option of the pax(1)utility. --posix Same as --format=posix. -V, --label=TEXT Create archive with volume name TEXT. If listing or extracting, use TEXT as a globbing pattern for volume name. Compression options -a, --auto-compress Use archive suffix to determine the compression program. -I, --use-compress-program=COMMAND Filter data through COMMAND. It must accept the -d option, for decompression. The argument can con‐ tain command line options. -j, --bzip2 Filter the archive through bzip2(1). -J, --xz Filter the archive through xz(1). --lzip Filter the archive through lzip(1). --lzma Filter the archive through lzma(1). --lzop Filter the archive through lzop(1). --no-auto-compress Do not use archive suffix to determine the compression program. -z, --gzip, --gunzip, --ungzip Filter the archive through gzip(1). -Z, --compress, --uncompress Filter the archive through compress(1). Local file selection --add-file=FILE Add FILE to the archive (useful if its name starts with a dash). --backup[=CONTROL] Backup before removal. The CONTROL argument, if supplied, controls the backup policy. Its valid val‐ ues are: none, off Never make backups. t, numbered Make numbered backups. nil, existing Make numbered backups if numbered backups exist, simple backups otherwise. never, simple Always make simple backups If CONTROL is not given, the value is taken from the VERSION_CONTROL environment variable. If it is not set, existing is assumed. -C, --directory=DIR Change to DIR before performing any operations. This option is order-sensitive, i.e. it affects all options that follow. --exclude=PATTERN Exclude files matching PATTERN, a glob(3)-style wildcard pattern. --exclude-backups Exclude backup and lock files. --exclude-caches Exclude contents of directories containing file CACHEDIR.TAG, except for the tag file itself. --exclude-caches-all Exclude directories containing file CACHEDIR.TAG and the file itself. --exclude-caches-under Exclude everything under directories containing CACHEDIR.TAG --exclude-ignore=FILE Before dumping a directory, see if it contains FILE. If so, read exclusion patterns from this file. The patterns affect only the directory itself. --exclude-ignore-recursive=FILE Same as --exclude-ignore, except that patterns from FILE affect both the directory and all its subdi‐ rectories. --exclude-tag=FILE Exclude contents of directories containing FILE, except for FILE itself. --exclude-tag-all=FILE Exclude directories containing FILE. --exclude-tag-under=FILE Exclude everything under directories containing FILE. --exclude-vcs Exclude version control system directories. --exclude-vcs-ignores Exclude files that match patterns read from VCS-specific ignore files. Supported files are: .cvsig‐ nore, .gitignore, .bzrignore, and .hgignore. -h, --dereference Follow symlinks; archive and dump the files they point to. --hard-dereference Follow hard links; archive and dump the files they refer to. -K, --starting-file=MEMBER Begin at the given member in the archive. --newer-mtime=DATE Work on files whose data changed after the DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --no-null Disable the effect of the previous --null option. --no-recursion Avoid descending automatically in directories. --no-unquote Do not unquote input file or member names. --no-verbatim-files-from Treat each line read from a file list as if it were supplied in the command line. I.e., leading and trailing whitespace is removed and, if the resulting string begins with a dash, it is treated as tar command line option. This is the default behavior. The --no-verbatim-files-from option is provided as a way to restore it after --verbatim-files-from option. This option is positional: it affects all --files-from options that occur after it in, until --verba‐ tim-files-from option or end of line, whichever occurs first. It is implied by the --no-null option. --null Instruct subsequent -T options to read null-terminated names verbatim (disables special handling of names that start with a dash). See also --verbatim-files-from. -N, --newer=DATE, --after-date=DATE Only store files newer than DATE. If DATE starts with / or . it is taken to be a file name; the ctime of that file is used as the date. --one-file-system Stay in local file system when creating archive. -P, --absolute-names Don"t strip leading slashes from file names when creating archives. --recursion Recurse into directories (default). --suffix=STRING Backup before removal, override usual suffix. Default suffix is ~, unless overridden by environment variable SIMPLE_BACKUP_SUFFIX. -T, --files-from=FILE Get names to extract or create from FILE. Unless specified otherwise, the FILE must contain a list of names separated by ASCII LF (i.e. one name per line). The names read are handled the same way as command line arguments. They undergo quote removal and word splitting, and any string that starts with a - is handled as tar command line option. If this behavior is undesirable, it can be turned off using the --verbatim-files-from option. The --null option instructs tar that the names in FILE are separated by ASCII NUL character, instead of LF. It is useful if the list is generated by find(1) -print0 predicate. --unquote Unquote file or member names (default). --verbatim-files-from Treat each line obtained from a file list as a file name, even if it starts with a dash. File lists are supplied with the --files-from (-T) option. The default behavior is to handle names supplied in file lists as if they were typed in the command line, i.e. any names starting with a dash are treated as tar options. The --verbatim-files-from option disables this behavior. This option affects all --files-from options that occur after it in the command line. Its effect is reverted by the --no-verbatim-files-from} option. This option is implied by the --null option. See also --add-file. -X, --exclude-from=FILE Exclude files matching patterns listed in FILE. File name transformations --strip-components=NUMBER Strip NUMBER leading components from file names on extraction. --transform=EXPRESSION, --xform=EXPRESSION Use sed replace EXPRESSION to transform file names. File name matching options These options affect both exclude and include patterns. --anchored Patterns match file name start. --ignore-case Ignore case. --no-anchored Patterns match after any / (default for exclusion). --no-ignore-case Case sensitive matching (default). --no-wildcards Verbatim string matching. --no-wildcards-match-slash Wildcards do not match /. --wildcards Use wildcards (default for exclusion). --wildcards-match-slash Wildcards match / (default for exclusion). Informative output --checkpoint[=N] Display progress messages every Nth record (default 10). --checkpoint-action=ACTION Run ACTION on each checkpoint. --clamp-mtime Only set time when the file is more recent than what was given with --mtime. --full-time Print file time to its full resolution. --index-file=FILE Send verbose output to FILE. -l, --check-links Print a message if not all links are dumped. --no-quote-chars=STRING Disable quoting for characters from STRING. --quote-chars=STRING Additionally quote characters from STRING. --quoting-style=STYLE Set quoting style for file and member names. Valid values for STYLE are literal, shell, shell-always, c, c-maybe, escape, locale, clocale. -R, --block-number Show block number within archive with each message. --show-omitted-dirs When listing or extracting, list each directory that does not match search criteria. --show-transformed-names, --show-stored-names Show file or archive names after transformation by --strip and --transform options. --totals[=SIGNAL] Print total bytes after processing the archive. If SIGNAL is given, print total bytes when this sig‐ nal is delivered. Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2. The SIG prefix can be omitted. --utc Print file modification times in UTC. -v, --verbose Verbosely list files processed. --warning=KEYWORD Enable or disable warning messages identified by KEYWORD. The messages are suppressed if KEYWORD is prefixed with no- and enabled otherwise. Multiple --warning messages accumulate. Keywords controlling general tar operation: all Enable all warning messages. This is the default. none Disable all warning messages. filename-with-nuls "%s: file name read contains nul character" alone-zero-block "A lone zero block at %s" Keywords applicable for tar --create: cachedir "%s: contains a cache directory tag %s; %s" file-shrank "%s: File shrank by %s bytes; padding with zeros" xdev "%s: file is on a different filesystem; not dumped" file-ignored "%s: Unknown file type; file ignored" "%s: socket ignored" "%s: door ignored" file-unchanged "%s: file is unchanged; not dumped" ignore-archive "%s: file is the archive; not dumped" file-removed "%s: File removed before we read it" file-changed "%s: file changed as we read it" Keywords applicable for tar --extract: existing-file "%s: skipping existing file" timestamp "%s: implausibly old time stamp %s" "%s: time stamp %s is %s s in the future" contiguous-cast "Extracting contiguous files as regular files" symlink-cast "Attempting extraction of symbolic links as hard links" unknown-cast "%s: Unknown file type "%c", extracted as normal file" ignore-newer "Current %s is newer or same age" unknown-keyword "Ignoring unknown extended header keyword "%s"" decompress-program Controls verbose description of failures occurring when trying to run alternative decompressor programs. This warning is disabled by default (unless --verbose is used). A common example of what you can get when using this warning is: $ tar --warning=decompress-program -x -f archive.Z tar (child): cannot run compress: No such file or directory tar (child): trying gzip This means that tar first tried to decompress archive.Z using compress, and, when that failed, switched to gzip. record-size "Record size = %lu blocks" Keywords controlling incremental extraction: rename-directory "%s: Directory has been renamed from %s" "%s: Directory has been renamed" new-directory "%s: Directory is new" xdev "%s: directory is on a different device: not purging" bad-dumpdir "Malformed dumpdir: "X" never used" -w, --interactive, --confirmation Ask for confirmation for every action. Compatibility options -o When creating, same as --old-archive. When extracting, same as --no-same-owner. Size suffixes Suffix Units Byte Equivalent b Blocks SIZE x 512 B Kilobytes SIZE x 1024 c Bytes SIZE G Gigabytes SIZE x 1024^3 K Kilobytes SIZE x 1024 k Kilobytes SIZE x 1024 M Megabytes SIZE x 1024^2 P Petabytes SIZE x 1024^5 T Terabytes SIZE x 1024^4 w Words SIZE x 2 RETURN VALUE Tar exit code indicates whether it was able to successfully perform the requested operation, and if not, what kind of error occurred. 0 Successful termination. 1 Some files differ. If tar was invoked with the --compare (--diff, -d) command line option, this means that some files in the archive differ from their disk counterparts. If tar was given one of the --create, --append or --update options, this exit code means that some files were changed while being archived and so the resulting archive does not contain the exact copy of the file set. 2 Fatal error. This means that some fatal, unrecoverable error occurred. If a subprocess that had been invoked by tar exited with a nonzero exit code, tar itself exits with that code as well. This can happen, for example, if a compression option (e.g. -z) was used and the external compres‐ sor program failed. Another example is rmt failure during backup to a remote device. SEE ALSO bzip2(1), compress(1), gzip(1), lzma(1), lzop(1), rmt(8), symlink(7), tar(5), xz(1). Complete tar manual: run info tar or use emacs(1) info mode to read it. Online copies of GNU tar documentation in various formats can be found at: http://www.gnu.org/software/tar/manual BUG REPORTS Report bugs to . COPYRIGHT Copyright © 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent per‐ mitted by law. TAR March 23, 2016 TAR(1)

В наши дни мы сталкиваемся с файлами архивов очень часто и на всех платформах: Windows, Mac или Linux. Это могут быть программы, резервные копии систем или баз данных или просто архив файлов. Нам также часто приходится создавать свои архивы в Linux, чтобы передать несколько файлов друзьям или загрузить на файлообменник. В виде архивов распространяются пакеты программ, исходные коды, а также много других файлов, распространяемых на просторах интернета. Научиться выполнять архивирование файлов в Linux через терминал очень важно, возможно это вам понадобиться, когда не будет доступа к графическому интерфейсу, или просто со временем в терминале станет более приятно работать.

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

Важно отметить, что архивирование в linux это не одно и то же что и сжатие файлов linux. Архивирование - это объединение нескольких небольших файлов в один, с целю более удобной последующей передачи, хранения, шифрования или сжатия. Как я уже сказал, архивация выполняется специальными утилитами. Мы не будем трогать архивацию файлов в графическом интерфейсе, вы с ними разберетесь сами, наша тема - терминал.

Самой популярной для Linux утилитой для архивации есть tar. Она используется почти везде, для архивации исходников, упаковки пакетов. Для сжатия используются другие утилиты, в зависимости от алгоритма сжатия, например, zip, bz, xz, lzma и т д. Сначала выполняется архивация, затем сжатие, отдельными программами. Автоматический запуск некоторых утилит сжатия для только что созданного архива поддерживается в tar и других подобных программах с помощью специальных опций.

Также полезной возможностью архивации есть шифрование. Но теперь давайте рассмотрим какие существуют утилиты, с помощью которых выполняется архивирование файлов linux и как ими пользоваться.

Tar

Tar - это стандартная утилита, с помощью которой выполняется архивирование файлов Linux. Постепенно из небольшой программы архивации она превратилась в мощный инструмент, поддерживающий работу со многими вариантами архивов и алгоритмами сжатия. Программа поддерживает большое количество параметров. Давайте рассмотрим ее синтаксис и основные параметры:

$ tar опцииf файл_для_записи /папка_файлами_для_архива

А теперь разберем основные опции:

  • A - добавить файл к архиву
  • c - создать архив в linux
  • d - сравнить файлы архива и распакованные файлы в файловой системе
  • j - сжать архив с помощью Bzip
  • z - сжать архив с помощью Gzip
  • r - добавить файлы в конец архива
  • t - показать содержимое архива
  • u - обновить архив относительно файловой системы
  • x - извлечь файлы из архива
  • v - показать подробную информацию о процессе работы
  • f - файл для записи архива
  • -C - распаковать в указанную папку
  • --strip-components - отбросить n вложенных папок

Теперь давайте рассмотрим архивирование файлов в Linux. Чтобы создать архив используйте такую команду:

tar -cvf archive.tar.gz /path/to/files

А чтобы распаковать архив tar linux:

tar -xvf archive.tar.gz

Очень просто запомнить для упаковки используется опция c - C reate, а для распаковки - x - eX tract.

Сжатый архив создается точно так же, только с опцией -z, это в случае, если использовалось шифрование gizp, если нужно bzip то применяется опция -j:

tar -zcvf archive.tar.gz /path/to/files

$ tar -zxvf archive.tar.gz

Например, рассмотрим как заархивировать папку в Linux:

tar -zcvf home.tar.gz ~/

Хотя можно поступить по-другому, тот же архив мы получим если сначала создать обычный архив с помощью tar, а потом сжать его утилитой для сжатия, только здесь мы получаем больше контроля над процессом сжатия:

gzip archive.tar

Также можно убрать сжатие:

gunzip archive.tar.gz

Утилиты сжатия мы рассмотрим ниже.

Чтобы добавить файл в архив используйте:

tar -rvf archive.tar file.txt

Для извлечения одного файла синтаксис тот же:

tar -xvf archive.tar file.txt

Можно извлечь несколько файлов по шаблону соответствия с помощью параметра wildcard, например, извлечем все php файлы:

tar -xvf archive.tar --wildcards "*.php"

По умолчанию распаковать архив tar linux можно в текущую папку с именем архива, чтобы распаковать в нужную папку используйте ключ -C:

tar -xvf archive.tar -C /path/to/dir

Стандартную утилиту рассмотрели, теперь кратко рассмотрим ее альтернативы. Их не так много, и большинство из них уже устаревшие.

Shar

Shar позволяет создавать самораспаковывающиеся архивы. По сути, это скрипт оболочки, и для распаковки ему необходима оболочка Bash или другая совместимая с Bourne Shell. У Shar есть несколько преимуществ, но также он потенциально небезопасный, так как архив представляет собой исполняемый файл.

Опции shar:

  • -o - сохранять архив в файл вместо стандартного вывода
  • -l - ограничить размер выходного файла
  • -L - ограничить размер выходного файла и разбить его на части
  • -n - имя архива не будет включено в заголовок
  • -a - разрешить автоматическую генерацию заголовков

Примеры использования shar для того чтобы заархивировать папку linux:

Создаем shar архив:

shar file_name.extension > filename.shar

Распаковываем shar архив:

Ar

ar - утилита для создания и управления архивами. В основном используется для архивации статических библиотек, но может быть использована для создания любых архивов. Раньше использовалась довольно часто но была вытеснена утилитой tar. Сейчас используется только для создания и обновления файлов статических библиотек.

  • - d - удалить модули из архива
  • - m - перемещение членов в архиве
  • - p - напечатать специфические члены архива
  • - q - быстрое добавление
  • - r - добавить члена к архиву
  • - s - создать индекс архива
  • - a - добавить новый файл к существующему архиву

Теперь рассмотрим примеры использования. Создадим статическую библиотеку libmath.a из объектных файлов substraction.o и division.o:

ar cr libmath.a substraction.o division.o

Теперь извлечем файлы из архива:

Таким образом, можно распаковать любую статическую библиотеку.

Cpio

cpio - означает Copy in and out (скопировать ввод и вывод). Это еще один стандартный архиватор для Linux. Активно используется в менеджере пакетов Red Hat, а также для создания initramfs. Архивация в Linux для обычных файлов с помощью этой программы не применяется.

Опции утилиты:

  • -a - сбросить время обращения к файлам после их копирования
  • -A - добавить файл
  • -d - создать каталоги при необходимости

Пример использования. Создаем cpio архив:

file1.o file2.o file3.o

ls | cpio -ov > /path/to/output_folder/obj.cpio

Распаковываем архив:

cpio -idv < /path/to folder/obj.cpio

Архивирование папки linux выполняется также само.

Сжатие архивов в Linux

Как создать архив в linux рассмотрели. Теперь давайте поговорим о сжатии. Как я говорил, для сжатия используются специальные утилиты. Рассмотрим кратко несколько из них

Gzip

Чаще всего применяется Gzip. Это стандартная утилита сжатия в Unix/Linux. Для декомпрессии используется gunzip или gzip -d Сначала рассмотрим ее синтаксис:

$ gzip опции файл

$ gunzip опции файл

Теперь разберем опции:

  • -c - выводить архив в стандартный вывод
  • -d - распаковать
  • -f - принудительно распаковывать или сжимать
  • -l - показать информацию об архиве
  • -r - рекурсивно перебирать каталоги
  • -0 - минимальный уровень сжатия
  • -9 - максимальный уровень сжатия

Примеры использования вы уже видели в описании утилиты tar. Например, выполним сжатие файла:

gzip -c файл > архив.gz

А теперь распакуем:

gunzip -c архив.gz

Но чтобы сжать папку в Linux вам придется сначала заархивировать ее с помощью tar, а уже потом сжать файл архива с помощью gzip.

Bzip

bzip2 - еще одна альтернативная утилита сжатия для Linux. Она более эффективная чем gzip, но работает медленнее. Для распаковки используйте утилиту bunzip2.

Описывать опции bzip2 я не буду, они аналогичны gzip. Чтобы создать архив в Linux используйте:

В текущем каталоге будет создан файл file.bz2

Lzma

Новый и высокоэффективный алгоритм сжатия. Синтаксис и опции тоже похожи на Gzip. Для распаковки используйте unlzma.

Xz

Еще один высокоэффективный алгоритм сжатия. Обратно совместимый с Lzma. Параметры вызова тоже похожи на Gzip.

Zip

Кроссплатформенная утилита для создания сжатых архивов формата zip. Совместимая с Windows реализациями этого алгоритма. Zip архивы очень часто используются для обмена файлами в интернете. С помощью этой утилиты можно сжимать как файлы, так и сжать папку linux.

Синтаксис утилиты:

$ zip опции файлы

$ unzip опции архив

Опции утилиты:

  • -d удалить файл из архива
  • -r - рекурсивно обходить каталоги
  • -0 - только архивировать, без сжатия
  • -9 - наилучший степень сжатия
  • -F - исправить zip файл
  • -e - шифровать файлы

Чтобы создать Zip архив в Linux используйте.

Утилита командной строки 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

Примеры

gz

Распаковка.gz файла:

tar -xvf archive.tar.gz

* при возникновении ошибки This does not look like a tar archive , можно воспользоваться командой gzip -d archive.tar.gz .

bz2

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

gzip

tar -xvzf archive.tar.gzip

* ключ z отвечает за работу с gzip.

tgz

Распаковывается, как 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 -czvf archive.tar.gz /wwwsite --exclude="sess_*"

* в данном примере мы создадим архив archive.tar.gz , в котором не будет файлов, начинающихся на sess_ .

Описание ключей tar

Команды для действия

* нельзя использовать несколько вышеперечисленных ключей в одной команде.

Дополнительные опции

Ключ Описание
--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-архивов с помощью практических примеров и подробных объяснений наиболее распространенных параметров Tar.

Что такое Tar?

Команда tar используется для создания архивов tar, путем преобразования группы файлов в архив. Она также имеет возможность извлекать архивы tar, отображать список файлов, включенных в архив, добавлять дополнительные файлы в существующий архив, а также различные другие виды операций.

Tar поддерживает широкий спектр программ сжатия, таких как gzip , bzip2 , lzip , lzma , lzop , xz и compress . При создании сжатых tar-архивов принято считать добавление суффикса компрессора к имени файла архива. Например, если архив был сжат с помощью gzip, он должен быть назван archive.tar.gz.

Tar был первоначально разработан для создания архивов при хранения файлов на магнитной ленте, поэтому он имеет свое название « T ape AR chive».

Существуют две версии tar, BSD tar и GNU tar с некоторыми функциональными отличиями. Большинство систем Linux поставляются с предустановленной GNU tar по умолчанию. Если у вас не установлен tar, рекомендуем сначало установить его следую нашей статьи .

Синтаксис командной строки

Прежде чем перейти к использованию команды tar, давайте начнем с рассмотрения базового синтаксиса.

Tar

  • OPERATION – Разрешается и требуется только один аргумент. Наиболее часто используемые операции:
    • --create (-c) – Создание нового tar-архива.
    • --extract (-x) – Извлечь весь архив или один или несколько файлов из архива.
    • --list (-t) – отобразить список файлов, включенных в архив
  • OPTIONS – Наиболее часто используемые операции:
    • --verbose (-v) – Показать файлы, обрабатываемые командой tar.
    • --file=archive=name (-f archive-name) – Указывает имя файла архива.
  • ARCHIVE_NAME – Название архива.
  • FILE_NAME(s) – список имен файлов, разделенных пробелами, которые нужно извлечь. Если не предусмотрено, весь архив будет извлечен.

При выполнении команды tar вы можете использовать длинную или краткую форму операций и параметров tar. Длинные формы более читабельны, а короткие формы – быстрее. Опции длинной формы имеют префикс двойной тире (--). Параметры короткой формы имеют префикс с одним тире (-), который можно опустить.

Создание Tar Archive

Используйте оператор -c для создания архива tar. Например, чтобы создать архивный файл с именем archive.tar из файлов с именем file1 , file2 , file3 выполните следующую команду:

Tar -cf archive.tar file1 file2 file3

Вот эквивалентная команда, использующая параметры длинной формы:

Tar --create --file=archive.tar file1 file2 file3

В следующем примере будет создан архив backup.tar из каталога /home/username:

Tar -cf backup.tar /home/username

Вы можете создавать архивы из содержимого одного или нескольких каталогов или файлов. По умолчанию каталоги архивируются рекурсивно, если не указан параметр --no-recursion . Используйте параметр -v , если хотите просмотреть файлы, которые обрабатываются.

Создание архива Tar Gz

Gzip – самый популярный алгоритм сжатия tar-файлов. При сжатии архивов tar с gzip имя архива должно заканчиваться либо tar.gz или tgz .

Чтобы создать архив tar.gz из заданных файлов, вы можете использовать следующую команду:

Tar -czf archive.tar.gz file1 file2

Опция -z сообщает tar сжать архив, используя алгоритм gzip .

Создание архива Tar Bz2

Другим популярным алгоритмом сжатия tar-файлов является bzip2. При сжатии архивов tar с bzip2 имя архива должно заканчиваться либо tar.bz2 либо tbz .

Когда указана опция -j , tar будет использовать алгоритм bzip2 сжатия архива.

Следующая команда создаст архив tar.bz2 из заданных файлов:

Tar -cjf archive.tar.bz2 file1 file2

Листинг архива Tar

Чтобы перечислить содержимое tar-архива, используйте операцию --list (-t).

Tar -tf archive.tar file1 file2 file3

Если вы укажете содержимое архива с помощью параметра --verbose (-v), tar будет печатать больше информации, например, владельца, размера файла, метки времени и т.д.:

Tar -tvf archive.tar -rw-r--r-- linuxize/users 0 2018-09-08 20:15 file1 -rw-r--r-- linuxize/users 0 2018-09-08 20:15 file2 -rw-r--r-- linuxize/users 0 2018-09-08 20:15 file3

Извлечение архива Tar

Для извлечения tar-архива используйте оператор --extract (-x) и укажите имя файла архива:

Tar -xf archive.tar

Также обычно добавляется опция -v для печати имен извлеченных файлов.

Tar -xvf archive.tar

По умолчанию tar будет извлекать содержимое архива в текущем рабочем каталоге. Используйте --directory (-C) для извлечения архивных файлов в определенном каталоге:

Например, чтобы извлечь содержимое архива в каталог /opt/files , вы можете использовать:

Tar -xf archive.tar -C /opt/files

Извлечение архивов Tar Gz и Tar Bz2

При извлечении сжатых архивов, например, tar.gz или tar.bz2 вам не нужно указывать параметр декомпрессии. Команда такая же, как при извлечении архива tar:

Tar -xf archive.tar.gz tar -xf archive.tar.bz2

Извлечение определенных файлов из tar-архива

Чтобы извлечь определенные файлы из архива tar, добавьте список имен файлов, разделенных пробелами, которые будут извлечены после имени архива:

Tar -xf archive.tar file1 file2

При извлечении файлов вы должны указать свои точные имена, включая путь, как напечатано --list (-t).

Извлечение одной или нескольких каталогов из архива аналогично извлечению файлов:

Tar -xf archive.tar dir1 dir2

Если вы попытаетесь извлечь файл, который не существует, появится сообщение об ошибке, подобное приведенному ниже:

Tar -xf archive.tar README tar: README: Not found in archive tar: Exiting with failure status due to previous errors

Извлечение файлов из архива Tar с помощью подстановочного знака

Чтобы извлечь файлы из архива на основе шаблона подстановочных знаков, используйте переключатель --wildcards и укажите шаблон, чтобы предотвратить интерпретацию оболочки.

Например, чтобы извлечь файлы, имена которых заканчиваются на.js (файлы Javascript), вы можете использовать:

Tar -xf archive.tar --wildcards "*.js"

Добавление файлов в существующий архив

Чтобы добавить файлы или каталоги в существующий архив tar, используйте операцию --append (-r).

Например, чтобы добавить файл с именем newfile в archive.tar, вы можете использовать:

Tar -rvf archive.tar newfile

Удаление файлов из tar-архива

Используйте операцию --delete для удаления файлов из архива.

Например, чтобы удалить файл с именем file1 из archive.tar, вы можете использовать:

Tar --delete -f archive.tar file1

Вывод

К настоящему времени у вас должно быть хорошее понимание того, как создавать и извлекать архивы tar.

tar - это архиватор от GNU. tar берёт несколько файлов и/или каталогов и объединяет их в один большой файл. Это позволяет вам сжать целое дерево каталогов, что невозможно сделать с помощью или bzip2. У tar"а есть много опций, которые подробно описаны на его странице руководства.

$ man tar tar -xvvf foo.tar extract foo.tar tar -xvvzf foo.tar.gz extract gzipped foo.tar.gz tar -cvvf foo.tar foo/ tar contents of folder foo in foo.tar

Часто используемые ключи команды tar

    C – создать (create) новый архив

    X – извлечь (extract) файлы из архива

    –delete – удалить (delete) файлы из архива

    R – добавить (append) файлы в существующий архив

    A – добавить (append) tar-файлы в существующий архив

    T – список файлов в архиве (содержимое архива)

    U – обновить (update) архив

    D – операция сравнения архива с заданной файловой системой

    Z – обработка архива с помощью Примеры использования gzip и gunzip . Сжатие или разжатие, в зависимости от комбинации сопутствующих ключей -c или -x.

    J – обработка архива с помощью bzip2. Сжатие или разжатие, в зависимости от комбинации сопутствующих ключей -c или -x.

tar запускается с обязательным указанием одного из основных действий, самые распространенные из которых - создание и распаковка архивов, далее задаются прочие параметры, зависящие от конкретной операции.

Наиболее общее использование tar заключается в распаковке и разархивировании пакета, загруженного с веб- или ftp-сайта. Большинство файлов имеют расширение.tar.gz. Довольно часто их называют “tarball”"ами. Это означает несколько файлов, заархивированных tar"ом, а затем сжатых gzip"ом. Вы также можете встретить файлы.tar.Z. По сути это то же самое, однако встречаются они в основном на старых системах Unix.

Кроме того вы можете натолкнуться на файлы.tar.bz2. В таком виде распространяются исходные тексты ядра, поскольку так они занимают меньше места для загрузки. Как вы уже наверное догадались, это файлы, заархивированные tar"ом и сжатые bzip"ом.

Вы можете извлечь все файлы из такого архива, воспользовавшись tar"ом с несколькими опциями командной строки. Разархивирование тарбола выполняется с помощью опции -z, которая означает, что сначала файл должен быть пропущен через gunzip, а уже потом распакован. Наиболее общий метод распаковки тарболов:

% tar -xvzf файл.tar.gz

Здесь довольно много опций. Что же они означают? Опция -x означает извлечение. Это важно, поскольку она сообщает tar"у, что именно нужно сделать со входным файлом. В данном случае он будет снова разбит на файлы, из которых он был “слеплен”. Опция -v означает включение подробного режима. При этом на экран будут выведены названия всех извлекаемых из архива файлов. Неплохо было бы использовать эту опцию, чтобы распаковка не выглядела слишком скучно. Вы также можете использовать -vv, чтобы вывод был ещё более подробным и вы получили ещё больше информации об извлекаемых файлах. Опция -z сообщает tar"у о том, что файл.tar.gz нужно сначала пропустить через gunzip. И, наконец, опция -f сообщает tar"у, что следующая строка в командной строке - это файл, с которым надо работать.

Существует несколько способов записи этой же команды. На старых системах, на которых отсутствует подходящая копия GNU tar, вы можете увидеть следующую запись этой же команды:

% gunzip файл.tar.gz | tar -xvf -

В этой команде файл сначала распаковывается, а результат отправляется в tar. Т.к. gzip по умолчанию записывает выходные данные на стандартный вывод, эта команда будет записывать распакованный файл на стандартный вывод. Затем конвейер перенаправляет этот поток в tar для распаковки. Знак “-” означает, что данные берутся со стандартного входа. Таким образом команда разархивирует поток данных, полученный из gzip, и запишет его на диск.

Другим способом записи первоначальной команды является убирание знака “-” перед опциями:

% tar xvzf файл.tar.gz

Также вы можете натолкнуться на bzip"нутый архив. Версия tar, представленная в Slackware Linux, может работать с ними точно так же, как и с gzip"нутыми архивами. Просто вместо опции -z вам нужно использовать -j:

% tar -xvjf файл.tar.bz2

Учтите, что tar будет сохранять извлечённые из архива файлы в текущий каталог. Поэтому, если у вас в /tmp есть архив, который вы хотите распаковать в свой домашний каталог, у вас есть несколько вариантов. Первый - архив можно переместить в ваш домашний каталог, а затем развернуть его с помощью tar. Второй - вы можете указать путь к архиву в командной строке. Третий - вы можете использовать опцию -C, чтобы разархивировать тарбол в указанный после этой опции каталог.

% cd $HOME % cp /tmp/файл.tar.gz . % tar -xvzf файл.tar.gz % cd $HOME % tar -xvzf /tmp/файл.tar.gz % cd / % tar -xvzf /tmp/файл.tar.gz -C $HOME

Все приведенные выше записи являются эквивалентными. В каждой из них архив разворачивается в ваш домашний каталог, а исходный сжатый архив остаётся на месте.

Итак, что же хорошего в том, что вы можете распаковывать архивы, если вы не можете создавать их? tar умеет делать и это. В большинстве случаев можно просто заменить опцию “-x” на “-c”.

% tar -cvzf файл.tar.gz .

В этой команде опция -c сообщает tar"у, что нужно создать архив, а опция -z пропускает полученный архив через gzip, чтобы сжать его. файл.tar.gz - это имя создаваемого файла.

Указание опции “-f” не всегда есть обязательным, однако в любом случае лучше её использовать. Без неё tar будет записывать свои данные на стандартный вывод, что обычно используется для перенаправления потока по конвейеру в другую программу, например, так:

% tar -cv файл.tar . | gpg --encrypt

Эта команда создаёт несжатый tar-архив с содержимым текущего каталога, а затем пропускает тарбол через программу gpg, которая шифрует и сжимает архив, делая невозможным его чтение кем-либо, у кого нет вашего секретного ключа.

tar через ssh

Если компьютер-источник и целевой компьютер связаны по LAN или WAN, то для экономии времени можно комбинировать использование SSH (Secure Shell) и tar для архивирования, копирования и извлечения файлов за один раз. Вот как это делать:

$ (cd ~/stuff; tar --create --gzip --file - *) | \ ssh destination tar --extract --gunzip --file --verbose -C stuff

В этой команде выполняется сразу несколько действий. Давайте разберем ее:

    Последовательность команд, заключенных в круглых скобках, называют вложенной оболочкой - subshell. Изменения, сделанные в subshell-оболочке - например, изменение каталога, - не повлияют на команду в целом, а затронут только среду вложенной оболочки. Поэтому первая управляющая последовательность - (cd ~/stuff; tar –create –gzip –file - *) меняет текущий рабочий каталог на ~/stuff, а затем запускает tar. Так как за вложенной оболочкой следует перенаправление в канал, то все результаты работы subshell посылаются в следующую на очереди команду.

    Как и много других UNIX-утилит, tar может писать в стандартный поток вывода (stdout) и читать из стандартного потока ввода (stdin). И stdout и stdin обычно обозначаются дефисом (-). Поэтому команда –create –file - создает архив в stdout.

    Канал (|) передает все результаты работы subshell в утилиту ssh, которая, в свою очередь, передает все необходимые данные с исходного компьютера на удаленный.

    Наконец, удаленный компьютер запускает собственный экземпляр утилиты tar для извлечения данных из архива. Теперь –extract –file - считывает архив из стандартного потока ввода. Опция -C принуждает tar на целевом компьютере сменить текущий рабочий каталог на stuff, прежде чем начать какие-либо операции разархивирования. Конечным результатом работы этой команды в целом будет передача архива через ssh и распаковка его в ~/stuff.

Итак, с помощью одной команды архив был создан, передан и распакован. Кстати, слегка изменив эту команду, можно копировать архив с удаленного компьютера на локальный и разархивировать его. Вот команда, которую для этого надо выполнить на локальном компьютере:

$ ssh destination cat archive.tgz | \ (cd ~/stuff; tar --extract --gunzip --file -)

Архив на удаленном компьютере будет открыт, затем поток байтов из cat будет послан во вложенную оболочку, которая сменит рабочий каталог, а затем извлечет архив. (Добавление -C ~/stuff к команде tar приведет к тем же результатам; пример показывает только то, что subshell тоже могут работать со входными данными.)

tar exclude

–exclude pattern (-W exclude=pattern) Не обрабатывать файлы или директории, которые совпадают с указанным шаблоном. Учтите, что исключения имеют приоритет над шаблонами или именами файлов, указанных в командной строке.

    Пример: Из директории test при архивировании tar исключить поддиректорию.svn tar -czf test1.tar.gz --exclude=".svn" test/

    Пример: При архивировании текущей директории и сжатием Примеры использования gzip и gunzip , исключить файл с расширениями.tar.gz .iso .deb .py $ tar -czf test.tar.gz *.* --exclude="*.tar.gz" --exclude="*.iso" --exclude="*.deb" --exclude="*.zip" --exclude="*.py"

tar с сохранением прав доступа

Создать архив с сохранением прав доступа. Ключ -p, –preserve-permissions, –same-permissions извлекать информацию o правах доступа к файлу (по умолчанию для суперпользователя)

Tar -cvpf archive.tar.gz dir1

Распаковать архив с сохранением прав доступа

Tar -xvpf archive.tar.gz

tar распаковать в нужную директорию

Чтобы распаковать архив в нужную директорию используется ключ -С

# man tar ... -C directory In c and r mode, this changes the directory before adding the following files. In x mode, change directories after opening the archive but before extracting entries from the archive. ...

Например, пример проверен для FreeBSD:

# tar -xvf /usr/home/darkfire/backup.ns.server.254/usr/ports/distfiles.tar -C /usr/ports/

tar split разбить архив на несколько частей

Split -b 1000m distfiles.tar distfiles.split.tar

В итоге вы получите много файликов типа

Distfiles.split.taraa distfiles.split.tarab distfiles.split.tarai

100m означает 100 мегабайт. Можете написать 100k - это будет 100 киллобайт. Собрать обратно их можно вот так:

Cat distfiles.split.tar* | tar zxvf -