Пакет: xz
- Версия
- 5.6.4
- Релиз
- 1.niceos5
- Архитектура
- x86_64
- Хэш GOST
- 7af749074620aa16eadbdb7d55c8ebf6fa579bac00835995ad9f9e9e23547bfc
- Хэш MD5
- 87e2296b3c4d4efccad86f9f9a2898e4
- Хэш SHA256
- a3c33e82ba300a919077fa5291fb7835b995cd8234cc548582fe3b4df04090f2
- Лицензия
- GPLv2+ и GPLv3+ и LGPLv2+
- Дата сборки
- 12 мая 2025 г.
- Размер
- 832,025 МиБ
- Совместимые ОС
- rpm файл:
- xz-5.6.4-1.niceos5.x86_64.rpm
Зависимости
Имя | Тип | Версия |
---|---|---|
/bin/sh | runtime | - |
/sbin/ldconfig | runtime | - |
libc.so.6()(64bit) | runtime | - |
libc.so.6(GLIBC_2.14)(64bit) | runtime | - |
libc.so.6(GLIBC_2.17)(64bit) | runtime | - |
libc.so.6(GLIBC_2.2.5)(64bit) | runtime | - |
libc.so.6(GLIBC_2.3)(64bit) | runtime | - |
libc.so.6(GLIBC_2.32)(64bit) | runtime | - |
libc.so.6(GLIBC_2.33)(64bit) | runtime | - |
libc.so.6(GLIBC_2.34)(64bit) | runtime | - |
libc.so.6(GLIBC_2.4)(64bit) | runtime | - |
libc.so.6(GLIBC_2.6)(64bit) | runtime | - |
liblzma.so.5()(64bit) | runtime | - |
liblzma.so.5(XZ_5.0)(64bit) | runtime | - |
liblzma.so.5(XZ_5.2)(64bit) | runtime | - |
liblzma.so.5(XZ_5.4)(64bit) | runtime | - |
liblzma.so.5(XZ_5.6.0)(64bit) | runtime | - |
rtld(GNU_HASH) | runtime | - |
xz-libs | runtime | - |
Граф зависимостей
История изменений
Дата | Автор | Сообщение |
---|---|---|
31 мар. 2025 г. | Stanislav Belikov <sbelikov@ncsgp.ru> | Первая сборка для xz |
Файлы пакета
-
-
- /usr/bin/lzcat 2 Б
- /usr/bin/lzcmp 6 Б
- /usr/bin/lzdiff 6 Б
- /usr/bin/lzegrep 6 Б
- /usr/bin/lzfgrep 6 Б
- /usr/bin/lzgrep 6 Б
- /usr/bin/lzless 6 Б
- /usr/bin/lzma 2 Б
- /usr/bin/lzmadec 17,18 КиБ
- /usr/bin/lzmainfo 16,844 КиБ
- /usr/bin/lzmore 6 Б
- /usr/bin/unlzma 2 Б
- /usr/bin/unxz 2 Б
- /usr/bin/xz 106,562 КиБ
- /usr/bin/xzcat 2 Б
- /usr/bin/xzcmp 6 Б
- /usr/bin/xzdec 17,18 КиБ
- /usr/bin/xzdiff 7,41 КиБ
- /usr/bin/xzegrep 6 Б
- /usr/bin/xzfgrep 6 Б
- /usr/bin/xzgrep 10,169 КиБ
- /usr/bin/xzless 2,327 КиБ
- /usr/bin/xzmore 2,182 КиБ
-
-
-
-
-
- /usr/share/locale/ca/LC_MESSAGES/xz.mo 30,287 КиБ
-
-
-
-
- /usr/share/locale/cs/LC_MESSAGES/xz.mo 15,074 КиБ
-
-
-
-
- /usr/share/locale/da/LC_MESSAGES/xz.mo 10,783 КиБ
-
-
-
-
- /usr/share/locale/de/LC_MESSAGES/xz.mo 31,797 КиБ
-
-
-
-
- /usr/share/locale/eo/LC_MESSAGES/xz.mo 29,276 КиБ
-
-
-
-
- /usr/share/locale/es/LC_MESSAGES/xz.mo 30,444 КиБ
-
-
-
-
- /usr/share/locale/fi/LC_MESSAGES/xz.mo 20,938 КиБ
-
-
-
-
- /usr/share/locale/fr/LC_MESSAGES/xz.mo 18,889 КиБ
-
-
-
-
- /usr/share/locale/hr/LC_MESSAGES/xz.mo 29,632 КиБ
-
-
-
-
- /usr/share/locale/hu/LC_MESSAGES/xz.mo 30,916 КиБ
-
-
-
-
- /usr/share/locale/it/LC_MESSAGES/xz.mo 18,682 КиБ
-
-
-
-
- /usr/share/locale/ko/LC_MESSAGES/xz.mo 30,742 КиБ
-
-
-
-
- /usr/share/locale/pl/LC_MESSAGES/xz.mo 29,894 КиБ
-
-
-
-
- /usr/share/locale/pt/LC_MESSAGES/xz.mo 18,547 КиБ
-
-
-
-
- /usr/share/locale/pt_BR/LC_MESSAGES/xz.mo 30,231 КиБ
-
-
-
-
- /usr/share/locale/ro/LC_MESSAGES/xz.mo 31,875 КиБ
-
-
-
-
- /usr/share/locale/sr/LC_MESSAGES/xz.mo 37,525 КиБ
-
-
-
-
- /usr/share/locale/sv/LC_MESSAGES/xz.mo 29,667 КиБ
-
-
-
-
- /usr/share/locale/tr/LC_MESSAGES/xz.mo 21,513 КиБ
-
-
-
-
- /usr/share/locale/uk/LC_MESSAGES/xz.mo 39,387 КиБ
-
-
-
-
- /usr/share/locale/vi/LC_MESSAGES/xz.mo 32,089 КиБ
-
-
-
-
- /usr/share/locale/zh_CN/LC_MESSAGES/xz.mo 28,31 КиБ
-
-
-
-
- /usr/share/locale/zh_TW/LC_MESSAGES/xz.mo 28,01 КиБ
-
-
-
-
-
- /usr/share/man/man1/lzcat.1.gz 7 Б
- /usr/share/man/man1/lzcmp.1.gz 11 Б
- /usr/share/man/man1/lzdiff.1.gz 11 Б
- /usr/share/man/man1/lzegrep.1.gz 11 Б
- /usr/share/man/man1/lzfgrep.1.gz 11 Б
- /usr/share/man/man1/lzgrep.1.gz 11 Б
- /usr/share/man/man1/lzless.1.gz 11 Б
- /usr/share/man/man1/lzma.1.gz 7 Б
- /usr/share/man/man1/lzmadec.1.gz 10 Б
- /usr/share/man/man1/lzmainfo.1.gz 668 Б
- /usr/share/man/man1/lzmore.1.gz 11 Б
- /usr/share/man/man1/unlzma.1.gz 7 Б
- /usr/share/man/man1/unxz.1.gz 7 Б
- /usr/share/man/man1/xz.1.gz 22,534 КиБ
- /usr/share/man/man1/xzcat.1.gz 7 Б
- /usr/share/man/man1/xzcmp.1.gz 11 Б
- /usr/share/man/man1/xzdec.1.gz 1,222 КиБ
- /usr/share/man/man1/xzdiff.1.gz 745 Б
- /usr/share/man/man1/xzegrep.1.gz 11 Б
- /usr/share/man/man1/xzfgrep.1.gz 11 Б
- /usr/share/man/man1/xzgrep.1.gz 958 Б
- /usr/share/man/man1/xzless.1.gz 737 Б
- /usr/share/man/man1/xzmore.1.gz 669 Б
-
-
-
-
Документация (man-страницы)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - сравнение сжатых файлов SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp и xzdiff сравнивают несжатое содержимое двух файлов. Несжатые данные и опции передаются в cmp(1) или diff(1), если не указан --help или --version. Если указаны оба file1 и file2, они могут быть несжатыми файлами или файлами в форматах, которые могут разархивировать xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1). Необходимые команды для разархивирования определяются по суффиксам имён файлов file1 и file2. Файл с неизвестным суффиксом предполагается либо несжатым, либо в формате, который может разархивировать xz(1). Если предоставлено только одно имя файла, file1 должен иметь суффикс поддерживаемого формата сжатия, и имя для file2 предполагается как file1 без суффикса формата сжатия. Команды lzcmp и lzdiff предоставлены для обратной совместимости с LZMA Utils. EXIT STATUS Если происходит ошибка разархивирования, код выхода равен 2. В противном случае используется код выхода cmp(1) или diff(1). SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - compare compressed files SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp and xzdiff compare uncompressed contents of two files. Uncom‐ pressed data and options are passed to cmp(1) or diff(1) unless --help or --version is specified. If both file1 and file2 are specified, they can be uncompressed files or files in formats that xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) can decompress. The required decompression commands are deter‐ mined from the filename suffixes of file1 and file2. A file with an unknown suffix is assumed to be either uncompressed or in a format that xz(1) can decompress. If only one filename is provided, file1 must have a suffix of a sup‐ ported compression format and the name for file2 is assumed to be file1 with the compression format suffix removed. The commands lzcmp and lzdiff are provided for backward compatibility with LZMA Utils. EXIT STATUS If a decompression error occurs, the exit status is 2. Otherwise the exit status of cmp(1) or diff(1) is used. SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZ(1) Утилиты XZ XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Сжатие или распаковка файлов .xz и .lzma SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz эквивалентен xz --decompress. xzcat эквивалентен xz --decompress --stdout. lzma эквивалентен xz --format=lzma. unlzma эквивалентен xz --format=lzma --decompress. lzcat эквивалентен xz --format=lzma --decompress --stdout. При написании скриптов, которые нуждаются в распаковке файлов, рекомендуется всегда использовать имя xz с подходящими аргументами (xz -d или xz -dc) вместо имен unxz и xzcat. DESCRIPTION xz — это универсальный инструмент сжатия данных с синтаксисом командной строки, похожим на gzip(1) и bzip2(1). Основной формат файлов — .xz, но также поддерживается устаревший формат .lzma, используемый в LZMA Utils, и необработанные сжатые потоки без заголовков контейнера. Кроме того, поддерживается распаковка формата .lz, используемого lzip. xz сжимает или распаковывает каждый файл в соответствии с выбранным режимом операции. Если файлы не указаны или указан файл -, xz читает из стандартного ввода и записывает обработанные данные в стандартный вывод. xz отказывается (выводит ошибку и пропускает файл) записывать сжатые данные в стандартный вывод, если он является терминалом. Аналогично, xz отказывается читать сжатые данные из стандартного ввода, если он является терминалом. Если не указан --stdout, файлы, отличные от -, записываются в новый файл, имя которого получается из имени исходного файла: • При сжатии суффикс целевого формата файла (.xz или .lzma) добавляется к имени исходного файла для получения имени целевого файла. • При распаковке суффиксы .xz, .lzma или .lz удаляются из имени файла для получения имени целевого файла. xz также распознает суффиксы .txz и .tlz и заменяет их на .tar. Если целевой файл уже существует, выводится ошибка и файл пропускается. Если не запись в стандартный вывод, xz выведет предупреждение и пропустит файл, если выполняется одно из следующих условий: • Файл не является обычным файлом. Символические ссылки не следуются и поэтому не считаются обычными файлами. • Файл имеет более одной жесткой ссылки. • Файл имеет установленными биты setuid, setgid или sticky. • Режим операции установлен на сжатие и файл уже имеет суффикс целевого формата файла (.xz или .txz при сжатии в формат .xz, и .lzma или .tlz при сжатии в формат .lzma). • Режим операции установлен на распаковку и файл не имеет суффикса любого из поддерживаемых форматов файлов (.xz, .txz, .lzma, .tlz или .lz). После успешного сжатия или распаковки файла xz копирует владельца, группу, разрешения, время доступа и время модификации из исходного файла в целевой файл. Если копирование группы не удалось, разрешения изменяются так, чтобы целевой файл не стал доступным для пользователей, у которых не было доступа к исходному файлу. xz пока не поддерживает копирование другой метаданных, такой как списки контроля доступа или расширенные атрибуты. Как только целевой файл успешно закрыт, исходный файл удаляется, если не указан --keep. Исходный файл никогда не удаляется, если вывод пишется в стандартный вывод или если произошла ошибка. Отправка сигнала SIGINFO или SIGUSR1 процессу xz заставляет его выводить информацию о прогрессе в стандартный вывод ошибок. Это имеет ограниченное использование, поскольку если стандартный вывод ошибок является терминалом, использование --verbose отобразит автоматически обновляющийся индикатор прогресса. Использование памяти Использование памяти xz варьируется от нескольких сотен килобайт до нескольких гигабайт в зависимости от настроек сжатия. Настройки, используемые при сжатии файла, определяют требования к памяти декомпрессора. Обычно декомпрессору требуется 5 % до 20 % от количества памяти, которое потребовалось компрессору при создании файла. Например, распаковка файла, созданного с xz -9, в настоящее время требует 65 MiB памяти. Тем не менее, возможно иметь файлы .xz, которые требуют нескольких гигабайт памяти для распаковки. Особенно пользователи старых систем могут найти возможность очень большого использования памяти раздражающей. Чтобы предотвратить неприятные сюрпризы, xz имеет встроенный лимитер использования памяти, который по умолчанию отключен. Хотя некоторые операционные системы предоставляют способы ограничения использования памяти процессами, полагаться на это не считалось достаточно гибким (например, использование ulimit(1) для ограничения виртуальной памяти может нарушить mmap(2)). Лимитер использования памяти можно включить с помощью опции командной строки --memlimit=limit. Часто удобнее включить лимитер по умолчанию, установив переменную среды XZ_DEFAULTS, например, XZ_DEFAULTS=--memlimit=150MiB. Возможна установка лимитов отдельно для сжатия и распаковки с помощью --memlimit-compress=limit и --memlimit-decompress=limit. Использование этих двух опций вне XZ_DEFAULTS редко полезно, поскольку один запуск xz не может выполнять одновременно сжатие и распаковку, и --memlimit=limit (или -M limit) короче для ввода в командной строке. Если указанный лимит использования памяти превышен при распаковке, xz выведет ошибку и распаковка файла завершится неудачей. Если лимит превышен при сжатии, xz попытается уменьшить настройки так, чтобы лимит больше не превышался (кроме случаев с --format=raw или --no-adjust). Таким образом, операция не завершится неудачей, если лимит не очень мал. Уменьшение настроек выполняется в шагах, которые не соответствуют пресетам уровней сжатия, например, если лимит немного меньше, чем требуется для xz -9, настройки уменьшатся только немного, а не до xz -8. Конкатенация и заполнение файлов .xz Возможна конкатенация файлов .xz как есть. xz будет распаковывать такие файлы, как будто это один файл .xz. Возможна вставка заполнения между конкатенированными частями или после последней части. Заполнение должно состоять из нулевых байтов, и его размер должен быть кратным четырем байтам. Это может быть полезно, например, если файл .xz хранится на носителе, который измеряет размеры файлов в блоках по 512 байт. Конкатенация и заполнение не допускаются для файлов .lzma или необработанных потоков. OPTIONS Суффиксы целых чисел и специальные значения В большинстве мест, где ожидается аргумент целого числа, поддерживается необязательный суффикс для удобного указания больших целых чисел. Между целым числом и суффиксом не должно быть пробелов. KiB Умножить целое число на 1 024 (2^10). Ki, k, kB, K и KB принимаются как синонимы KiB. MiB Умножить целое число на 1 048 576 (2^20). Mi, m, M и MB принимаются как синонимы MiB. GiB Умножить целое число на 1 073 741 824 (2^30). Gi, g, G и GB принимаются как синонимы GiB. Специальное значение max можно использовать, чтобы указать максимальное поддерживаемое целое значение опцией. Режим операции Если несколько опций режима операции указаны, последняя вступает в силу. -z, --compress Сжатие. Это режим операции по умолчанию, когда ни одна опция режима операции не указана и другой режим не подразумевается из имени команды (например, unxz подразумевает --decompress). После успешного сжатия исходный файл удаляется, если вывод пишется не в стандартный вывод или не указан --keep. -d, --decompress, --uncompress Распаковка. После успешной распаковки исходный файл удаляется, если вывод пишется не в стандартный вывод или не указан --keep. -t, --test Проверить целостность сжатых файлов. Эта опция эквивалентна --decompress --stdout, за исключением того, что распакованные данные отбрасываются вместо записи в стандартный вывод. Файлы не создаются и не удаляются. -l, --list Вывести информацию о сжатых файлах. Несжатый вывод не производится, и файлы не создаются или не удаляются. В режиме списка программа не может читать сжатые данные из стандартного ввода или из других несекционируемых источников. По умолчанию список показывает базовую информацию о файлах, по одному файлу на строку. Для получения более подробной информации используйте также опцию --verbose. Для еще большей информации используйте --verbose дважды, но учтите, что это может быть медленно, поскольку получение всей дополнительной информации требует многих поисков. Ширина подробного вывода превышает 80 символов, так что перенаправление вывода в, например, less -S может быть удобным, если терминал недостаточно широкий. Точный вывод может варьироваться между версиями xz и разными локалями. Для машинно-читаемого вывода используйте --robot --list. Модификаторы операции -k, --keep Не удалять входные файлы. С xz 5.2.6 эта опция также заставляет xz сжимать или распаковывать, даже если вход — это символическая ссылка на обычный файл, имеет более одной жесткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. В более ранних версиях это делалось только с --force. -f, --force Эта опция имеет несколько эффектов: • Если целевой файл уже существует, удалить его перед сжатием или распаковкой. • Сжимать или распаковывать, даже если вход — это символическая ссылка на обычный файл, имеет более одной жесткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. • При использовании с --decompress --stdout, если xz не может распознать тип исходного файла, скопировать исходный файл как есть в стандартный вывод. Это позволяет использовать xzcat --force как cat(1) для файлов, которые не были сжаты с xz. Обратите внимание, что в будущем xz может поддерживать новые форматы сжатых файлов, что может сделать xz распаковывать больше типов файлов вместо копирования их как есть в стандартный вывод. --format=format можно использовать, чтобы ограничить xz распаковкой только одного формата файла. -c, --stdout, --to-stdout Записывать сжатые или распакованные данные в стандартный вывод вместо файла. Это подразумевает --keep. --single-stream Распаковывать только первый .xz-поток и молча игнорировать возможные оставшиеся входные данные после потока. Нормально такие завершающие данные заставляют xz вывести ошибку. xz никогда не распаковывает более одного потока из файлов .lzma или необработанных потоков, но эта опция все равно заставляет xz игнорировать возможные завершающие данные после файла .lzma или необработанного потока. Эта опция не имеет эффекта, если режим операции не --decompress или --test. --no-sparse Отключить создание разреженных файлов. По умолчанию, если распаковывается в обычный файл, xz пытается сделать файл разреженным, если распакованные данные содержат длинные последовательности бинарных нулей. Это также работает при записи в стандартный вывод, если стандартный вывод подключен к обычному файлу и выполняются определенные дополнительные условия для безопасности. Создание разреженных файлов может сэкономить место на диске и ускорить распаковку, уменьшив объем ввода/вывода на диск. -S .suf, --suffix=.suf При сжатии использовать .suf как суффикс для целевого файла вместо .xz или .lzma. Если не запись в стандартный вывод и исходный файл уже имеет суффикс .suf, выводится предупреждение и файл пропускается. При распаковке распознавать файлы с суффиксом .suf в дополнение к файлам с суффиксами .xz, .txz, .lzma, .tlz или .lz. Если исходный файл имеет суффикс .suf, он удаляется для получения имени целевого файла. При сжатии или распаковке необработанных потоков (--format=raw) суффикс всегда должен указываться, если не запись в стандартный вывод, поскольку для необработанных потоков нет суффикса по умолчанию. --files[=file] Читать имена файлов для обработки из file; если file omitted, имена файлов читаются из стандартного ввода. Имена файлов должны заканчиваться символом новой строки. Точка (-) считается обычным именем файла; она не означает стандартный ввод. Если имена файлов также указаны в аргументах командной строки, они обрабатываются перед именами, прочитанными из file. --files0[=file] Это идентично --files[=file], за исключением того, что каждое имя файла должно заканчиваться нулевым символом. Основные опции формата файлов и сжатия -F format, --format=format Указать формат файла для сжатия или распаковки: auto Это значение по умолчанию. При сжатии auto эквивалентно xz. При распаковке формат входного файла определяется автоматически. Обратите внимание, что необработанные потоки (созданные с --format=raw) не могут быть определены автоматически. xz Сжимать в формат файла .xz или принимать только файлы .xz при распаковке. lzma, alone Сжимать в устаревший формат файла .lzma или принимать только файлы .lzma при распаковке. Альтернативное имя alone предоставлено для обратной совместимости с LZMA Utils. lzip При распаковке принимать только файлы .lz. Сжатие не поддерживается. Поддерживаются версия формата 0 и нерасширенная версия 1. Файлы версии 0 создавались lzip 1.3 и старше. Такие файлы редко встречаются, но могут быть найдены в архивах файлов, поскольку несколько исходных пакетов были выпущены в этом формате. Люди могут иметь старые личные файлы в этом формате. Поддержка распаковки версии формата 0 была удалена в lzip 1.18. lzip 1.4 и новее создают файлы версии формата 1. Расширение маркера синхронизированного сброса для версии формата 1 было добавлено в lzip 1.6. Это расширение редко используется и не поддерживается xz (диагностируется как поврежденный ввод). raw Сжимать или распаковывать необработанный поток (без заголовков). Это предназначено только для продвинутых пользователей. Для декодирования необработанных потоков вам нужно использовать --format=raw и явно указать цепочку фильтров, которая обычно хранилась бы в заголовках контейнера. -C check, --check=check Указать тип проверки целостности. Проверка рассчитывается из несжатых данных и хранится в файле .xz. Эта опция имеет эффект только при сжатии в формат .xz; формат .lzma не поддерживает проверки целостности. Проверка целостности (если она есть) проверяется при распаковке файла .xz. Поддерживаемые типы проверок: none Не рассчитывать проверку целостности вообще. Это обычно плохая идея. Это может быть полезно, когда целостность данных проверяется другими средствами. crc32 Рассчитать CRC32 с использованием полинома из IEEE-802.3 (Ethernet). crc64 Рассчитать CRC64 с использованием полинома из ECMA-182. Это значение по умолчанию, поскольку оно немного лучше, чем CRC32, для обнаружения поврежденных файлов, и разница в скорости незначительна. sha256 Рассчитать SHA-256. Это немного медленнее, чем CRC32 и CRC64. Целостность заголовков .xz всегда проверяется с CRC32. Изменить или отключить это невозможно. --ignore-check Не проверять проверку целостности сжатых данных при распаковке. Значения CRC32 в заголовках .xz все равно будут проверены нормально. Не используйте эту опцию, если вы не знаете, что делаете. Возможные причины использования этой опции: • Попытка восстановления данных из поврежденного файла .xz. • Увеличение скорости распаковки. Это имеет значение в основном с SHA-256 или с файлами, которые сжаты очень хорошо. Рекомендуется не использовать эту опцию для этой цели, если целостность файла проверяется внешне другим способом. -0 ... -9 Выбрать пресет уровня сжатия. По умолчанию -6. Если указано несколько пресетов уровней, последний вступает в силу. Если уже указана пользовательская цепочка фильтров, установка пресета уровня сжатия очищает пользовательскую цепочку фильтров. Различия между пресетами больше, чем у gzip(1) и bzip2(1). Выбранные настройки сжатия определяют требования к памяти декомпрессора, так что использование слишком высокого пресета уровня может сделать распаковку болезненной на старой системе с малым объемом RAM. В частности, не стоит слепо использовать -9 для всего, как часто бывает с gzip(1) и bzip2(1). -0 ... -3 Это относительно быстрые пресеты. -0 иногда быстрее, чем gzip -9, при гораздо лучшем сжатии. Более высокие часто имеют скорость, сравнимую с bzip2(1), с сопоставимым или лучшим коэффициентом сжатия, хотя результаты сильно зависят от типа сжимаемых данных. -4 ... -6 Хорошее до очень хорошего сжатия при разумном использовании памяти декомпрессора даже для старых систем. -6 — это значение по умолчанию, которое обычно является хорошим выбором для распространения файлов, которые должны быть распаковываемыми даже на системах с всего 16 MiB RAM. (-5e или -6e также стоит рассмотреть. См. --extreme.) -7 ... -9 Это как -6, но с более высокими требованиями к памяти компрессора и декомпрессора. Это полезно только при сжатии файлов больше 8 MiB, 16 MiB и 32 MiB соответственно. На одном и том же оборудовании скорость распаковки примерно постоянна в количестве байт сжатых данных в секунду. Другими словами, чем лучше сжатие, тем быстрее обычно будет распаковка. Это также означает, что количество несжатого вывода, произведенного в секунду, может сильно варьироваться. В следующей таблице суммируются особенности пресетов: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Описания столбцов: • DictSize — размер словаря LZMA2. Зря тратить память на словарь больше, чем размер несжатого файла. Поэтому не стоит использовать пресеты -7 ... -9, если в них нет реальной необходимости. При -6 и ниже, количество потраченной впустую памяти обычно достаточно мало, чтобы это не имело значения. • CompCPU — упрощенное представление настроек LZMA2, влияющих на скорость сжатия. Размер словаря также влияет на скорость, так что, хотя CompCPU одинаков для уровней -6 ... -9, более высокие уровни все равно склонны быть немного медленнее. Для получения еще более медленного и, возможно, лучшего сжатия см. --extreme. • CompMem — требования к памяти компрессора в однопоточном режиме. Это может немного варьироваться между версиями xz. • DecMem — требования к памяти декомпрессора. То есть, настройки сжатия определяют требования к памяти декомпрессора. Точное использование памяти декомпрессором немного больше размера словаря LZMA2, но значения в таблице округлены вверх до следующего полного MiB. Требования к памяти в многопоточном режиме значительно выше, чем в однопоточном. С значением --block-size по умолчанию, каждый поток требует 3*3*DictSize плюс CompMem или DecMem. Например, четыре потока с пресетом -6 требуют 660–670 MiB памяти. -e, --extreme Использовать более медленную версию выбранного пресета уровня сжатия (-0 ... -9), чтобы, hopefully, получить немного лучший коэффициент сжатия, но с неудачей это может сделать его хуже. Использование памяти декомпрессором не затрагивается, но использование памяти компрессором немного увеличивается при пресетах -0 ... -3. Поскольку есть два пресета с размерами словарей 4 MiB и 8 MiB, пресеты -3e и -5e используют немного более быстрые настройки (нижний CompCPU), чем -4e и -6e соответственно. Таким образом, ни два пресета не являются идентичными. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB Например, всего четыре пресета используют словарь 8 MiB, порядок от самого быстрого к самому медленному — -5, -6, -5e и -6e. --fast --best Эти — несколько вводящие в заблуждение псевдонимы для -0 и -9 соответственно. Они предоставлены только для обратной совместимости с LZMA Utils. Избегайте использования этих опций. --block-size=size При сжатии в формат .xz разделить входные данные на блоки по size байт. Блоки сжимаются независимо друг от друга, что помогает с многопоточностью и делает возможной ограниченную случайную распаковку. Эта опция обычно используется для переопределения размера блока по умолчанию в многопоточном режиме, но ее можно использовать и в однопоточном режиме. В многопоточном режиме примерно трижды size байт будет выделено в каждом потоке для буферизации ввода и вывода. Значение по умолчанию — три размера словаря LZMA2 или 1 MiB, в зависимости от того, что больше. Типично хорошее значение — 2–4 раза размер словаря LZMA2 или как минимум 1 MiB. Использование size меньше размера словаря LZMA2 — трата RAM, поскольку буфер словаря LZMA2 никогда не будет полностью использован. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Эта информация о размере необходима для многопоточной распаковки. В однопоточном режиме разделение блоков по умолчанию не выполняется. Установка этой опции не влияет на использование памяти. Информация о размере не хранится в заголовках блоков, поэтому файлы, созданные в однопоточном режиме, не будут идентичны файлам, созданным в многопоточном режиме. Отсутствие информации о размере также означает, что xz не сможет распаковывать файлы в многопоточном режиме. --block-list=items При сжатии в формат .xz начинать новый блок с необязательной пользовательской цепочкой фильтров после указанных интервалов несжатых данных. items — список, разделенный запятыми. Каждый элемент состоит из необязательного номера цепочки фильтров от 0 до 9, за которым следует двоеточие (:) и обязательный размер несжатых данных. Пропуск элемента (две или более последовательные запятые) — сокращение для использования размера и фильтров предыдущего элемента. Если входной файл больше суммы размеров в items, последний элемент повторяется до конца файла. Специальное значение 0 можно использовать как последний размер, чтобы указать, что остаток файла должен быть закодирован как один блок. Альтернативную цепочку фильтров для каждого блока можно указать в сочетании с опциями --filters1=filters ... --filters9=filters. Эти опции определяют цепочки фильтров с идентификатором от 1 до 9. Цепочка фильтров 0 можно использовать для ссылки на цепочку фильтров по умолчанию, которая является той же, что и без указания цепочки фильтров. Идентификатор цепочки фильтров можно использовать перед несжатым размером, за которым следует двоеточие (:). Например, если указать --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB, то блоки будут созданы с использованием: • Цепочки фильтров, указанной в --filters1 и 2 MiB входа. • Цепочки фильтров, указанной в --filters3 и 2 MiB входа. • Цепочки фильтров, указанной в --filters2 и 4 MiB входа. • Цепочки фильтров, указанной в --filters2 и 4 MiB входа. • Цепочки фильтров по умолчанию и 2 MiB входа. • Цепочки фильтров по умолчанию и 4 MiB входа для каждого блока до конца входа. Если указать размер, превышающий размер блока энкодера (значение по умолчанию в многопоточном режиме или значение, указанное с --block-size=size), энкодер создаст дополнительные блоки, сохраняя границы, указанные в items. Например, если указать --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB и входной файл 80 MiB, получите 11 блоков: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10 и 1 MiB. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Это не делается в однопоточном режиме, так что закодированный вывод не будет идентичным тому, что в многопоточном режиме. --flush-timeout=timeout При сжатии, если прошло более timeout миллисекунд (положительное целое число) с предыдущего сброса и чтение дополнительного ввода заблокировано, все ожидающие входные данные сбрасываются из энкодера и становятся доступными в выходном потоке. Это может быть полезно, если xz используется для сжатия данных, передаваемых по сети. Малые значения timeout делают данные доступными на принимающей стороне с малой задержкой, но большие значения дают лучший коэффициент сжатия. Эта функция отключена по умолчанию. Если эта опция указана несколько раз, последняя вступает в силу. Специальное значение timeout 0 можно использовать для явного отключения этой функции. Эта функция недоступна в не-POSIX-системах. Эта функция все еще экспериментальна. В настоящее время xz непригоден для распаковки потока в реальном времени из-за того, как xz выполняет буферизацию. --memlimit-compress=limit Установить лимит использования памяти для сжатия. Если эта опция указана несколько раз, последняя вступает в силу. Если настройки сжатия превышают лимит, xz попытается уменьшить настройки вниз, чтобы лимит больше не превышался, и выведет уведомление о том, что автоматическая корректировка была произведена. Корректировки производятся в следующем порядке: уменьшение количества потоков, переключение в однопоточный режим, если даже один поток в многопоточном режиме превышает лимит, и, наконец, уменьшение размера словаря LZMA2. При сжатии с --format=raw или если указан --no-adjust, может быть уменьшено только количество потоков, поскольку это можно сделать без влияния на сжатый вывод. Если лимит не может быть достигнут даже с корректировками, описанными выше, выводится ошибка и xz выходит с кодом выхода 1. Лимит можно указать несколькими способами: • Лимит может быть абсолютным значением в байтах. Использование суффикса целого числа, такого как MiB, может быть полезным. Пример: --memlimit-compress=80MiB • Лимит может быть указан как процент от общего физического объема памяти (RAM). Это может быть полезно, особенно при установке переменной XZ_DEFAULTS в скрипте инициализации оболочки, который общий для разных компьютеров. Таким образом лимит автоматически больше на системах с большим объемом памяти. Пример: --memlimit-compress=70% • Лимит можно сбросить до значения по умолчанию, установив его в 0. В настоящее время это эквивалентно установке лимита в max (нет лимита использования памяти). Для 32-битного xz есть специальный случай: если лимит был бы больше 4020 MiB, лимит устанавливается в 4020 MiB. На MIPS32 используется 2000 MiB. (Значения 0 и max не затрагиваются этим. Похожая функция не существует для распаковки.) Это может быть полезно, когда 32-битный исполняемый файл имеет доступ к 4 GiB адресного пространства (2 GiB на MIPS32), в то время как, надеемся, не причиняет вреда в других ситуациях. См. также раздел Использование памяти. --memlimit-decompress=limit Установить лимит использования памяти для распаковки. Это также влияет на режим --list. Если операция невозможна без превышения лимита, xz выведет ошибку и распаковка файла завершится неудачей. См. --memlimit-compress=limit для возможных способов указания лимита. --memlimit-mt-decompress=limit Установить лимит использования памяти для многопоточной распаковки. Это может повлиять только на количество потоков; это никогда не заставит xz отказаться от распаковки файла. Если limit слишком мал, чтобы позволить какую-либо многопоточность, лимит игнорируется и xz продолжит в однопоточном режиме. Обратите внимание, что если также используется --memlimit-decompress, он всегда применяется и к однопоточному, и к многопоточному режимам, так что эффективный лимит для многопоточности никогда не будет выше, чем лимит, установленный с --memlimit-decompress. В отличие от других опций лимита использования памяти, --memlimit-mt-decompress=limit имеет системно-специфическое значение лимита по умолчанию. xz --info-memory можно использовать, чтобы увидеть текущее значение. Эта опция и ее значение лимита по умолчанию существуют, потому что без какого-либо лимита многопоточный декомпрессор мог бы выделить безумное количество памяти для некоторых входных файлов. Если значение лимита по умолчанию слишком низкое на вашей системе, вы можете увеличить лимит, но никогда не устанавливайте его в значение больше, чем объем usable RAM, поскольку с подходящими входными файлами xz попытается использовать это количество памяти даже с малым количеством потоков. Выход из памяти или подкачка не улучшит производительность распаковки. См. --memlimit-compress=limit для возможных способов указания лимита. Установка limit в 0 сбрасывает лимит до значения по умолчанию, специфичного для системы. -M limit, --memlimit=limit, --memory=limit Это эквивалентно указанию --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Вывести ошибку и выйти, если лимит использования памяти не может быть достигнут без корректировки настроек, влияющих на сжатый вывод. То есть, это предотвращает переключение энкодера из многопоточного режима в однопоточный режим и уменьшение размера словаря LZMA2. Даже при использовании этой опции количество потоков может быть уменьшено, чтобы соответствовать лимиту использования памяти, поскольку это не влияет на сжатый вывод. Автоматическая корректировка всегда отключена при создании необработанных потоков (--format=raw). -T threads, --threads=threads Указать количество рабочих потоков. Установка threads в специальное значение 0 заставляет xz использовать до такого количества потоков, сколько процессор(ы) системы поддерживают. Фактическое количество потоков может быть меньше threads, если входной файл недостаточно большой для потоков с заданными настройками или если использование большего количества потоков превысит лимит использования памяти. Однопоточный и многопоточный компрессоры производят разный вывод. Однопоточный компрессор даст наименьший размер файла, но только вывод от многопоточного компрессора может быть распакован с использованием нескольких потоков. Установка threads в 1 использует однопоточный режим. Установка threads в любое другое значение, включая 0, использует многопоточный компрессор, даже если система поддерживает только один аппаратный поток. (xz 5.2.x использовал однопоточный режим в этой ситуации.) Чтобы использовать многопоточный режим с одним потоком, установите threads в +1. Префикс + не имеет эффекта с значениями, отличными от 1. Лимит использования памяти все равно может заставить xz переключиться в однопоточный режим, если не используется --no-adjust. Поддержка префикса + была добавлена в xz 5.4.0. Если запрошено автоматическое количество потоков и не указан лимит использования памяти, будет использоваться системно-специфический лимит использования памяти по умолчанию, чтобы, возможно, ограничить количество потоков. Это мягкий лимит в том смысле, что он игнорируется, если количество потоков становится одним, так что мягкий лимит никогда не остановит xz от сжатия или распаковки. Этот лимит по умолчанию не заставит xz переключиться из многопоточного режима в однопоточный режим. Активные лимиты можно увидеть с xz --info-memory. В настоящее время единственный метод потоков — разделить вход на блоки и сжать их независимо друг от друга. Размер блока по умолчанию зависит от уровня сжатия и может быть переопределен с опцией --block-size=size. Многопоточная распаковка работает только на файлах, которые содержат несколько блоков с информацией о размере в заголовках блоков. Все достаточно большие файлы, сжатые в многопоточном режиме, удовлетворяют этому условию, но файлы, сжатые в однопоточном режиме, нет, даже если использовался --block-size=size. Значение threads по умолчанию — 0. В xz 5.4.x и старше значение по умолчанию — 1. Пользовательские цепочки фильтров компрессора Пользовательская цепочка фильтров позволяет указывать настройки сжатия подробно вместо reliance на настройки, связанные с пресетами. Когда указана пользовательская цепочка фильтров, опции пресетов (-0 ... -9 и --extreme), указанные ранее в командной строке, забываются. Если опция пресета указана после одной или нескольких опций пользовательской цепочки фильтров, новый пресет вступает в силу, и пользовательские опции цепочки фильтров, указанные ранее, забываются. Цепочка фильтров сравнима с конвейером в командной строке. При сжатии несжатый вход поступает в первый фильтр, чей вывод поступает в следующий фильтр (если он есть). Вывод последнего фильтра записывается в сжатый файл. Максимальное количество фильтров в цепочке — четыре, но обычно цепочка фильтров имеет только один или два фильтра. Многие фильтры имеют ограничения на их положение в цепочке фильтров: некоторые фильтры могут работать только как последний фильтр в цепочке, некоторые только как нефинальный, а некоторые работают в любом положении в цепочке. В зависимости от фильтра, это ограничение либо inherent к дизайну фильтра, либо существует для предотвращения проблем безопасности. Пользовательскую цепочку фильтров можно указать двумя разными способами. Опции --filters=filters и --filters1=filters ... --filters9=filters позволяют указывать всю цепочку фильтров в одной опции с использованием синтаксиса строки фильтров liblzma. В качестве альтернативы цепочку фильтров можно указать, используя одну или несколько отдельных опций фильтров в порядке, в котором они должны быть в цепочке. То есть, порядок отдельных опций фильтров значим! При декодировании необработанных потоков (--format=raw) цепочку фильтров следует указывать в том же порядке, в котором она была указана при сжатии. Любые отдельные фильтры или опции пресетов, указанные до полной опции цепочки (--filters=filters), будут забыты. Отдельные фильтры, указанные после полной опции цепочки, сбросят цепочку фильтров. И полные, и отдельные опции фильтров принимают опции, специфичные для фильтра, в виде списка, разделенного запятыми. Дополнительные запятые в опциях игнорируются. Каждая опция имеет значение по умолчанию, так что укажите те, которые вы хотите изменить. Чтобы увидеть всю цепочку фильтров и опции, используйте xz -vv (то есть, используйте --verbose дважды). Это работает также для просмотра опций цепочки фильтров, используемых пресетами. --filters=filters Указать полную цепочку фильтров или пресет в одной опции. Каждый фильтр можно разделить пробелами или двумя дефисами (--). filters может потребоваться заключить в кавычки в командной строке оболочки, чтобы оно анализировалось как одна опция. Для обозначения опций используйте : или =. Пресет можно предварить - и за ним следовать нулю или более флагам. Единственный поддерживаемый флаг — e для применения тех же опций, что и --extreme. --filters1=filters ... --filters9=filters Указать до девяти дополнительных цепочек фильтров, которые можно использовать с --block-list. Например, при сжатии архива с исполняемыми файлами, за которыми следуют текстовые файлы, исполняемая часть могла бы использовать цепочку фильтров с фильтром BCJ, а текстовая часть — только фильтр LZMA2. --filters-help Вывести сообщение помощи, описывающее, как указывать пресеты и пользовательские цепочки фильтров в опциях --filters и --filters1=filters ... --filters9=filters, и выйти успешно. --lzma1[=options] --lzma2[=options] Добавить фильтр LZMA1 или LZMA2 в цепочку фильтров. Эти фильтры можно использовать только как последний фильтр в цепочке. LZMA1 — устаревший фильтр, который поддерживается почти исключительно из-за устаревшего формата файла .lzma, который поддерживает только LZMA1. LZMA2 — обновленная версия LZMA1 для устранения некоторых практических проблем LZMA1. Формат .xz использует LZMA2 и не поддерживает LZMA1. Скорость сжатия и коэффициенты LZMA1 и LZMA2 практически одинаковы. LZMA1 и LZMA2 имеют один и тот же набор опций: preset=preset Сбросить все опции LZMA1 или LZMA2 на preset. Preset состоит из целого числа, за которым может следовать модификаторы пресета в виде одной буквы. Целое число может быть от 0 до 9, соответствующее опциям командной строки -0 ... -9. Единственный поддерживаемый модификатор в настоящее время — e, который соответствует --extreme. Если пресет не указан, значения опций LZMA1 или LZMA2 по умолчанию берутся из пресета 6. dict=size Размер словаря (буфера истории) указывает, сколько байт недавно обработанных несжатых данных хранится в памяти. Алгоритм пытается найти повторяющиеся последовательности байтов (совпадения) в несжатых данных и заменить их ссылками на данные, находящиеся в настоящее время в словаре. Чем больше словарь, тем выше шанс найти совпадение. Таким образом, увеличение размера словаря обычно улучшает коэффициент сжатия, но словарь больше, чем несжатый файл, — трата памяти. Типичный размер словаря — от 64 KiB до 64 MiB. Минимум — 4 KiB. Максимум для сжатия в настоящее время 1.5 GiB (1536 MiB). Декомпрессор уже поддерживает словари до одного байта меньше 4 GiB, что является максимумом для форматов потоков LZMA1 и LZMA2. Размер словаря и поискатель совпадений (mf) вместе определяют использование памяти энкодером LZMA1 или LZMA2. Для распаковки требуется тот же (или больший) размер словаря, который использовался при сжатии, таким образом, использование памяти декомпрессором определяется размером словаря, использованным при сжатии. Заголовки .xz хранят размер словаря либо как 2^n, либо как 2^n + 2^(n-1), так что эти размеры несколько предпочтительны для сжатия. Другие размеры будут округлены вверх при хранении в заголовках .xz. lc=lc Указать количество бит контекста литералов. Минимум — 0, максимум — 4; значение по умолчанию — 3. Кроме того, сумма lc и lp не должна превышать 4. Все байты, которые не могут быть закодированы как совпадения, кодируются как литералы. То есть, литералы — это просто 8-битные байты, которые кодируются по одному. Кодирование литералов предполагает, что самые высокие lc бит предыдущего несжатого байта коррелируют со следующим байтом. Например, в типичном английском тексте заглавная буква часто следует за строчной буквой, и строчная буква обычно следует за другой строчной буквой. В наборе символов US-ASCII самые высокие три бита — 010 для заглавных букв и 011 для строчных букв. Когда lc как минимум 3, кодирование литералов может использовать это свойство в несжатых данных. Значение по умолчанию (3) обычно хорошее. Если вы хотите максимальное сжатие, протестируйте lc=4. Иногда это помогает немного, а иногда ухудшает сжатие. Если оно ухудшает, протестируйте lc=2 тоже. lp=lp Указать количество бит позиции литералов. Минимум — 0, максимум — 4; значение по умолчанию — 0. lp влияет на то, какое выравнивание в несжатых данных предполагается при кодировании литералов. См. pb ниже для дополнительной информации о выравнивании. pb=pb Указать количество бит позиции. Минимум — 0, максимум — 4; значение по умолчанию — 2. pb влияет на то, какое выравнивание в несжатых данных предполагается в общем. Значение по умолчанию означает четырехбайтное выравнивание (2^pb=2^2=4), что часто является хорошим выбором, когда нет лучшей догадки. Когда выравнивание известно, установка pb соответственно может немного уменьшить размер файла. Например, для текстовых файлов с однобайтным выравниванием (US-ASCII, ISO-8859-*, UTF-8), установка pb=0 может немного улучшить сжатие. Для UTF-16 текста pb=1 — хороший выбор. Если выравнивание — нечетное число, как 3 байта, pb=0 может быть лучшим выбором. Хотя предполагаемое выравнивание можно скорректировать с pb и lp, LZMA1 и LZMA2 все равно немного предпочитают 16-байтное выравнивание. Стоит учитывать это при проектировании форматов файлов, которые, вероятно, будут часто сжиматься с LZMA1 или LZMA2. mf=mf Поискатель совпадений сильно влияет на скорость энкодера, использование памяти и коэффициент сжатия. Обычно поискатели совпадений Hash Chain быстрее, чем Binary Tree. Значение по умолчанию зависит от пресета: 0 использует hc3, 1–3 используют hc4, а остальные — bt4. Поддерживаемые поискатели совпадений. Формулы использования памяти ниже — приблизительные оценки, которые ближе к реальности, когда dict — степень двух. hc3 Hash Chain с хэшированием 2- и 3-байтов Минимальное значение для nice: 3 Использование памяти: dict * 7.5 (если dict <= 16 MiB); dict * 5.5 + 64 MiB (если dict > 16 MiB) hc4 Hash Chain с хэшированием 2-, 3- и 4-байтов Минимальное значение для nice: 4 Использование памяти: dict * 7.5 (если dict <= 32 MiB); dict * 6.5 (если dict > 32 MiB) bt2 Binary Tree с хэшированием 2-байтов Минимальное значение для nice: 2 Использование памяти: dict * 9.5 bt3 Binary Tree с хэшированием 2- и 3-байтов Минимальное значение для nice: 3 Использование памяти: dict * 11.5 (если dict <= 16 MiB); dict * 9.5 + 64 MiB (если dict > 16 MiB) bt4 Binary Tree с хэшированием 2-, 3- и 4-байтов Минимальное значение для nice: 4 Использование памяти: dict * 11.5 (если dict <= 32 MiB); dict * 10.5 (если dict > 32 MiB) mode=mode Режим сжатия указывает метод анализа данных, производимых поискателем совпадений. Поддерживаемые режимы — fast и normal. Значение по умолчанию — fast для пресетов 0–3 и normal для пресетов 4–9. Обычно fast используется с поискателями совпадений Hash Chain, а normal — с Binary Tree. Это также то, что делают пресеты. nice=nice Указать, что считается хорошей длиной для совпадения. Как только найдено совпадение как минимум nice байт, алгоритм перестает искать, возможно, лучшие совпадения. nice может быть 2–273 байтами. Более высокие значения склонны давать лучший коэффициент сжатия за счет скорости. Значение по умолчанию зависит от пресета. depth=depth Указать максимальную глубину поиска в поискателе совпадений. Значение по умолчанию — специальное значение 0, которое заставляет компрессор определять разумную глубину из mf и nice. Разумная глубина для Hash Chains — 4–100, а для Binary Trees — 16–1000. Использование очень высоких значений для depth может сделать энкодер крайне медленным для некоторых файлов. Избегайте установки depth больше 1000, если вы готовы прервать сжатие в случае, если оно занимает слишком много времени. При декодировании необработанных потоков (--format=raw) LZMA2 нужен только размер словаря. LZMA1 также нужен lc, lp и pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Добавить фильтр ветвления/вызова/прыжка (BCJ) в цепочку фильтров. Эти фильтры можно использовать только как нефинальный фильтр в цепочке. Фильтр BCJ преобразует относительные адреса в машинном коде в их абсолютные аналоги. Это не изменяет размер данных, но повышает избыточность, что может помочь LZMA2 произвести на 0–15 % меньший файл .xz. Фильтры BCJ всегда обратимы, так что использование фильтра BCJ для неправильного типа данных не приведет к потере данных, хотя это может немного ухудшить коэффициент сжатия. Фильтры BCJ очень быстрые и используют незначительное количество памяти. У этих фильтров BCJ известны проблемы, связанные с коэффициентом сжатия: • Некоторые типы файлов, содержащих исполняемый код (например, объектные файлы, статические библиотеки и модули ядра Linux), имеют адреса в инструкциях, заполненные заполнительными значениями. Эти фильтры BCJ все равно выполнят преобразование адреса, что сделает сжатие хуже для этих файлов. • Если фильтр BCJ применяется к архиву, возможно, что это сделает коэффициент сжатия хуже, чем без использования фильтра BCJ. Например, если в архиве есть похожие или даже идентичные исполняемые файлы, то фильтрация, вероятно, сделает файлы менее похожими, и, таким образом, сжатие хуже. Содержимое нефайловых файлов в том же архиве тоже может иметь значение. На практике нужно попробовать с фильтром BCJ и без него, чтобы увидеть, что лучше в каждой ситуации. Разные наборы инструкций имеют разное выравнивание: исполняемый файл должен быть выровнен по кратному этого значения в входных данных, чтобы фильтр работал. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit или 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Поскольку отфильтрованные данные BCJ обычно сжимаются с LZMA2, коэффициент сжатия может быть немного улучшен, если опции LZMA2 установлены так, чтобы соответствовать выравниванию выбранного фильтра BCJ. Примеры: • Фильтр IA-64 имеет выравнивание 16 байт, так что pb=4,lp=4,lc=0 хорош с LZMA2 (2^4=16). • Код RISC-V имеет выравнивание 2 или 4 байта в зависимости от того, содержит ли файл 16-битные сжатые инструкции (расширение C). При использовании 16-битных инструкций pb=2,lp=1,lc=3 или pb=1,lp=1,lc=3 хорош. При отсутствии 16-битных инструкций pb=2,lp=2,lc=2 — лучший. readelf -h можно использовать, чтобы проверить, появляется ли "RVC" на строке "Flags". • ARM64 всегда имеет выравнивание 4 байта, так что pb=2,lp=2,lc=2 — лучший. • Фильтр x86 — исключение. Обычно хорошо придерживаться значений по умолчанию LZMA2 (pb=2,lp=0,lc=3) при сжатии исполняемых файлов x86. Все фильтры BCJ поддерживают одни и те же опции: start=offset Указать начальный смещение, которое используется при преобразовании между относительными и абсолютными адресами. Смещение должно быть кратным выравниванию фильтра (см. таблицу выше). Значение по умолчанию — ноль. На практике значение по умолчанию хорошее; указание пользовательского смещения почти никогда не полезно. --delta[=options] Добавить фильтр Delta в цепочку фильтров. Фильтр Delta можно использовать только как нефинальный фильтр в цепочке. В настоящее время поддерживается только простое вычисление дельты по байтам. Это может быть полезно при сжатии, например, несжатых растровых изображений или несжатого PCM-аудио. Однако специальные алгоритмы могут дать значительно лучшие результаты, чем Delta + LZMA2. Это верно, особенно для аудио, которое сжимается быстрее и лучше, например, с flac(1). Поддерживаемые опции: dist=distance Указать расстояние вычисления дельты в байтах. distance должно быть 1–256. Значение по умолчанию — 1. Например, с dist=2 и входом из восьми байт A1 B1 A2 B3 A3 B5 A4 B7 вывод будет A1 B1 01 02 01 02 01 02. Другие опции -q, --quiet Подавлять предупреждения и уведомления. Укажите это дважды, чтобы подавить ошибки тоже. Эта опция не влияет на код выхода. То есть, даже если предупреждение было подавлено, код выхода для указания предупреждения все равно используется. -v, --verbose Быть подробным. Если стандартный вывод ошибок подключен к терминалу, xz отобразит индикатор прогресса. Указание --verbose дважды даст еще более подробный вывод. Индикатор прогресса показывает следующую информацию: • Процент завершения отображается, если размер входного файла известен. То есть, процент не может быть показан в конвейерах. • Количество сжатых данных, произведенных (при сжатии) или потребленных (при распаковке). • Количество несжатых данных, потребленных (при сжатии) или произведенных (при распаковке). • Коэффициент сжатия, который рассчитывается делением количества обработанных сжатых данных на количество обработанных несжатых данных. • Скорость сжатия или распаковки. Это измеряется как количество несжатых данных, потребленных (сжатие) или произведенных (распаковка) в секунду. Она отображается после того, как прошло несколько секунд с момента запуска xz обработки файла. • Прошедшее время в формате M:SS или H:MM:SS. • Оставшееся время отображается только когда размер входного файла известен и прошло несколько секунд с момента запуска xz обработки файла. Время показано в менее точном формате, который никогда не имеет двоеточий, например, 2 min 30 s. Когда стандартный вывод ошибок не является терминалом, --verbose заставит xz вывести имя файла, сжатый размер, несжатый размер, коэффициент сжатия и, возможно, скорость и прошедшее время в одной строке в стандартный вывод ошибок после сжатия или распаковки файла. Скорость и прошедшее время включаются только когда операция заняла как минимум несколько секунд. Если операция не завершилась, например, из-за прерывания пользователем, также выводится процент завершения, если размер входного файла известен. -Q, --no-warn Не устанавливать код выхода в 2, даже если обнаружено условие, заслуживающее предупреждения. Эта опция не влияет на уровень подробности, так что для того, чтобы не отображать предупреждения и не изменять код выхода, нужно использовать и --quiet, и --no-warn. --robot Выводить сообщения в формате, удобном для разбора машинами. Это предназначено для облегчения написания фронтендов, которые хотят использовать xz вместо liblzma, что может быть в случае с различными скриптами. Вывод с этой опцией включенной предназначен для стабильности между релизами xz. См. раздел ROBOT MODE для деталей. --info-memory Вывести в человекочитаемом формате, сколько физической памяти (RAM) и сколько процессорных потоков, по мнению xz, имеет система, и лимиты использования памяти для сжатия и распаковки, и выйти успешно. -h, --help Вывести сообщение помощи, описывающее наиболее часто используемые опции, и выйти успешно. -H, --long-help Вывести сообщение помощи, описывающее все функции xz, и выйти успешно. -V, --version Вывести номер версии xz и liblzma в человекочитаемом формате. Для получения вывода, удобного для разбора машинами, укажите --robot перед --version. ROBOT MODE Режим робота активируется с опцией --robot. Это делает вывод xz легче для разбора другими программами. В настоящее время --robot поддерживается только вместе с --list, --filters-help, --info-memory и --version. В будущем он будет поддерживаться для сжатия и распаковки. Режим списка xz --robot --list использует вывод, разделенный табуляцией. Первый столбец каждой строки содержит строку, которая указывает тип информации, найденной на этой строке: name Это всегда первая строка при начале списка файла. Второй столбец на строке — имя файла. file Эта строка содержит общую информацию о файле .xz. Эта строка всегда выводится после строки name. stream Эта строка типа используется только когда указан --verbose. Здесь столько строк stream, сколько потоков в файле .xz. block Эта строка типа используется только когда указан --verbose. Здесь столько строк block, сколько блоков в файле .xz. Строки block показываются после всех строк stream; разные типы строк не перемежаются. summary Эта строка типа используется только когда указан --verbose дважды. Эта строка выводится после всех строк block. Как и строка file, строка summary содержит общую информацию о файле .xz. totals Эта строка всегда последняя строка вывода списка. Она показывает общие количества и размеры. Столбцы строк file: 2. Количество потоков в файле 3. Общее количество блоков в потоке(ах) 4. Сжатый размер файла 5. Несжатый размер файла 6. Коэффициент сжатия, например, 0.123. Если коэффициент больше 9.999, выводится три тире (---) вместо коэффициента. 7. Список имен проверок целостности, разделенный запятыми. Для известных типов проверок используются следующие строки: None, CRC32, CRC64 и SHA-256. Для неизвестных типов проверок используется Unknown-N, где N — Check ID в десятичном виде (одна или две цифры). 8. Общий размер заполнения потока в файле Столбцы строк stream: 2. Номер потока (первый поток — 1) 3. Количество блоков в потоке 4. Сжатый начальный смещение 5. Несжатый начальный смещение 6. Сжатый размер (не включает заполнение потока) 7. Несжатый размер 8. Коэффициент сжатия 9. Имя проверки целостности 10. Размер заполнения потока Столбцы строк block: 2. Номер потока, содержащего этот блок 3. Номер блока относительно начала потока (первый блок — 1) 4. Номер блока относительно начала файла 5. Сжатый начальный смещение относительно начала файла 6. Несжатый начальный смещение относительно начала файла 7. Общий сжатый размер блока (включает заголовки) 8. Несжатый размер 9. Коэффициент сжатия 10. Имя проверки целостности Если указан --verbose дважды, в строках block добавляются дополнительные столбцы. Они не отображаются с одним --verbose, поскольку получение этой информации требует многих поисков и, таким образом, может быть медленно: 11. Значение проверки целостности в шестнадцатеричном виде 12. Размер заголовка блока 13. Флаги блока: c указывает, что присутствует сжатый размер, а u указывает, что присутствует несжатый размер. Если флаг не установлен, выводится тире (-) для сохранения длины строки фиксированной. Новые флаги могут быть добавлены в конец строки в будущем. 14. Размер фактических сжатых данных в блоке (это исключает заголовок блока, заполнение блока и поля проверки) 15. Количество памяти (в байтах), требуемое для распаковки этого блока с этой версией xz 16. Цепочка фильтров. Обратите внимание, что большинство опций, использованных во время сжатия, не могут быть известны, поскольку в заголовках .xz хранятся только опции, необходимые для распаковки. Столбцы строк summary: 2. Количество памяти (в байтах), требуемое для распаковки этого файла с этой версией xz 3. yes или no, указывающее, имеют ли все заголовки блоков как сжатый, так и несжатый размер, хранящийся в них С xz 5.1.2alpha: 4. Минимальная версия xz, required для распаковки файла Столбцы строк totals: 2. Количество потоков 3. Количество блоков 4. Сжатый размер 5. Несжатый размер 6. Средний коэффициент сжатия 7. Список имен проверок целостности, присутствовавших в файлах, разделенный запятыми 8. Размер заполнения потока 9. Количество файлов. Это здесь, чтобы сохранить порядок предыдущих столбцов таким же, как в строках file. Если указан --verbose дважды, в строке totals добавляются дополнительные столбцы: 10. Максимальное количество памяти (в байтах), required для распаковки файлов с этой версией xz 11. yes или no, указывающее, имеют ли все заголовки блоков как сжатый, так и несжатый размер, stored в них С xz 5.1.2alpha: 12. Минимальная версия xz, required для распаковки файла Будущие версии могут добавить новые типы строк, и новые столбцы могут быть добавлены к существующим типам строк, но существующие столбцы не будут изменены. Помощь по фильтрам xz --robot --filters-help выводит поддерживаемые фильтры в следующем формате: filter:option=<value>,option=<value>... filter Имя фильтра option Имя опции, специфичной для фильтра value Диапазоны значений чисел отображаются как <min-max>. Выборы значений строк показаны в < > и разделены символом |. Каждый фильтр выводится на своей строке. Информация о лимите памяти xz --robot --info-memory выводит одну строку с несколькими столбцами, разделенными табуляцией: 1. Общий объем физической памяти (RAM) в байтах. 2. Лимит использования памяти для сжатия в байтах (--memlimit-compress). Специальное значение 0 указывает значение по умолчанию, которое для однопоточного режима такое же, как отсутствие лимита. 3. Лимит использования памяти для распаковки в байтах (--memlimit-decompress). Специальное значение 0 указывает значение по умолчанию, которое для однопоточного режима такое же, как отсутствие лимита. 4. С xz 5.3.4alpha: Использование памяти для многопоточной распаковки в байтах (--memlimit-mt-decompress). Это никогда не ноль, потому что системно-специфическое значение по умолчанию, shown в столбце 5, используется, если лимит не указан явно. Это также никогда не больше значения в столбце 3, даже если указано большее значение с --memlimit-mt-decompress. 5. С xz 5.3.4alpha: Системно-специфическое значение лимита использования памяти по умолчанию, которое используется для ограничения количества потоков при сжатии с автоматическим количеством потоков (--threads=0) и без указанного лимита использования памяти (--memlimit-compress). Это также используется как значение по умолчанию для --memlimit-mt-decompress. 6. С xz 5.3.4alpha: Количество доступных процессорных потоков. В будущем вывод xz --robot --info-memory может иметь больше столбцов, но никогда не больше одной строки. Версия xz --robot --version выводит номер версии xz и liblzma в следующем формате: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Основная версия. YYY Дополнительная версия. Четные числа стабильны. Нечетные числа — альфа- или бета-версии. ZZZ Уровень патча для стабильных релизов или просто счетчик для версий разработки. S Стабильность. 0 — альфа, 1 — бета, и 2 — стабильная. S должно быть всегда 2, когда YYY четное. XYYYZZZS одинаковы в обеих строках, если xz и liblzma из одного релиза XZ Utils. Примеры: 4.999.9beta — 49990091 и 5.0.0 — 50000002. EXIT STATUS 0 Все хорошо. 1 Произошла ошибка. 2 Произошло что-то, заслуживающее предупреждения, но реальных ошибок не произошло. Уведомления (не предупреждения или ошибки), выведенные в стандартный вывод ошибок, не влияют на код выхода. ENVIRONMENT xz разбирает списки опций, разделенные пробелами, из переменных среды XZ_DEFAULTS и XZ_OPT, в этом порядке, перед разбором опций из командной строки. Обратите внимание, что только опции разбираются из переменных среды; все нефции тихо игнорируются. Разбор выполняется с getopt_long(3), который используется также для аргументов командной строки. XZ_DEFAULTS Пользовательские или системные опции по умолчанию. Обычно это устанавливается в скрипте инициализации оболочки для включения лимитера использования памяти xz по умолчанию. Исключая скрипты инициализации оболочки и подобные специальные случаи, скрипты никогда не должны устанавливать или сбрасывать XZ_DEFAULTS. XZ_OPT Это для передачи опций xz, когда невозможно установить опции напрямую в командной строке xz. Это случай, когда xz запускается скриптом или инструментом, например, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Скрипты могут использовать XZ_OPT, например, для установки специфичных для скрипта опций сжатия по умолчанию. Все равно рекомендуется позволить пользователям переопределять XZ_OPT, если это разумно. Например, в скриптах sh(1) можно использовать что-то вроде этого: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY Синтаксис командной строки xz практически является надмножеством lzma, unlzma и lzcat из LZMA Utils 4.32.x. В большинстве случаев возможно заменить LZMA Utils на XZ Utils без нарушения существующих скриптов. Тем не менее, есть некоторые несоответствия, которые иногда могут вызвать проблемы. Пресеты уровней сжатия Нумерация пресетов уровней сжатия не идентична в xz и LZMA Utils. Самое важное отличие — как размеры словарей сопоставляются разным пресетам. Размер словаря примерно равен использованию памяти декомпрессором. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB Различия размеров словарей влияют и на использование памяти компрессором, но есть некоторые другие различия между LZMA Utils и XZ Utils, которые делают разницу еще больше: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB Пресет по умолчанию в LZMA Utils — -7, в то время как в XZ Utils — -6, так что оба используют словарь 8 MiB по умолчанию. Потоковые vs. нефпотоковые файлы .lzma Несжатый размер файла может быть храниться в заголовке .lzma. LZMA Utils делает это при сжатии обычных файлов. Альтернатива — отметить, что несжатый размер неизвестен, и использовать маркер конца полезной нагрузки, чтобы указать, где декомпрессор должен остановиться. LZMA Utils использует этот метод, когда несжатый размер неизвестен, что является случаем, например, в конвейерах. xz поддерживает распаковку файлов .lzma с маркером конца полезной нагрузки или без него, но все файлы .lzma, созданные xz, будут использовать маркер конца полезной нагрузки и иметь несжатый размер, отмеченный как неизвестный в заголовке .lzma. Это может быть проблемой в некоторых необычных ситуациях. Например, декомпрессор .lzma в встроенном устройстве может работать только с файлами, у которых известен несжатый размер. Если вы столкнетесь с этой проблемой, вам нужно использовать LZMA Utils или LZMA SDK для создания файлов .lzma с известным несжатым размером. Неподдерживаемые файлы .lzma Формат .lzma позволяет значения lc до 8 и значения lp до 4. LZMA Utils может распаковывать файлы с любым lc и lp, но всегда создает файлы с lc=3 и lp=0. Создание файлов с другими lc и lp возможно с xz и с LZMA SDK. Реализация фильтра LZMA1 в liblzma требует, чтобы сумма lc и lp не превышала 4. Таким образом, файлы .lzma, которые превышают это ограничение, не могут быть распакованы с xz. LZMA Utils создает только файлы .lzma, у которых размер словаря — 2^n (степень двух), но принимает файлы с любым размером словаря. liblzma принимает только файлы .lzma, у которых размер словаря — 2^n или 2^n + 2^(n-1). Это для уменьшения ложных срабатываний при обнаружении файлов .lzma. Эти ограничения не должны быть проблемой на практике, поскольку практически все файлы .lzma были сжаты с настройками, которые liblzma примет. Завершающий мусор При распаковке LZMA Utils тихо игнорируют все после первого потока .lzma. В большинстве ситуаций это ошибка. Это также означает, что LZMA Utils не поддерживают распаковку сконкатенированных файлов .lzma. Если после первого потока .lzma остались данные, xz считает файл поврежденным, если не указан --single-stream. Это может нарушить темные скрипты, которые предполагали, что завершающий мусор игнорируется. NOTES Сжатый вывод может варьироваться Точный сжатый вывод, произведенный из одного и того же несжатого входного файла, может варьироваться между версиями XZ Utils, даже если опции сжатия идентичны. Это потому, что энкодер может быть улучшен (быстрее или лучше сжатие) без влияния на формат файла. Вывод может варьироваться даже между разными сборками одной версии XZ Utils, если используются разные опции сборки. Вышеуказанное означает, что как только будет реализован --rsyncable, результирующие файлы не обязательно будут rsyncable, если старые и новые файлы были сжаты с одной версией xz. Эта проблема может быть исправлена, если часть реализации энкодера будет заморожена, чтобы сохранить rsyncable вывод стабильным между версиями xz. Встроенные декомпрессоры .xz Встроенные реализации декомпрессоров .xz, такие как XZ Embedded, не обязательно поддерживают файлы, созданные с типами проверок целостности, отличными от none и crc32. Поскольку значение по умолчанию — --check=crc64, вам нужно использовать --check=none или --check=crc32 при создании файлов для встроенных систем. За пределами встроенных систем все декомпрессоры формата .xz поддерживают все типы проверок, или, по крайней мере, могут распаковывать файл без проверки целостности, если конкретная проверка не поддерживается. XZ Embedded поддерживает фильтры BCJ, но только с смещением начала по умолчанию. EXAMPLES Основы Сжать файл foo в foo.xz с использованием уровня сжатия по умолчанию (-6) и удалить foo, если сжатие успешно: xz foo Распаковать bar.xz в bar и не удалять bar.xz, даже если распаковка успешна: xz -dk bar.xz Создать baz.tar.xz с пресетом -4e (-4 --extreme), который медленнее, чем значение по умолчанию -6, но требует меньше памяти для сжатия и распаковки (48 MiB и 5 MiB соответственно): tar cf - baz | xz -4e > baz.tar.xz Смесь сжатых и несжатых файлов может быть распакована в стандартный вывод с одной командой: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Параллельное сжатие многих файлов На GNU и *BSD find(1) и xargs(1) можно использовать для параллельного сжатия многих файлов: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 Опция -P xargs(1) устанавливает количество параллельных процессов xz. Лучшее значение для опции -n зависит от количества файлов, подлежащих сжатию. Если файлов всего несколько, значение, вероятно, должно быть 1; с десятками тысяч файлов 100 или даже больше может быть подходящим, чтобы уменьшить количество процессов xz, которые xargs(1) в конечном итоге создаст. Опция -T1 для xz указана, чтобы заставить его работать в однопоточном режиме, поскольку xargs(1) используется для контроля количества параллельности. Режим робота Рассчитать, сколько байт было сэкономлено в общей сложности после сжатия нескольких файлов: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' Скрипт может захотеть знать, что он использует достаточно новую версию xz. Следующий скрипт sh(1) проверяет, что номер версии инструмента xz как минимум 5.0.0. Этот метод совместим со старыми бета-версиями, которые не поддерживали опцию --robot: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Пользовательские цепочки фильтров компрессора Самое простое использование пользовательских цепочек фильтров — настройка пресета LZMA2. Это может быть полезно, потому что пресеты охватывают только подмножество потенциально полезных комбинаций настроек сжатия. Столбцы CompCPU таблиц из описаний опций -0 ... -9 и --extreme полезны при настройке пресетов LZMA2. Вот релевантные части, собранные из этих двух таблиц: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 Если вы знаете, что файл требует довольно большого словаря (например, 32 MiB), чтобы сжиматься хорошо, но вы хотите сжимать его быстрее, чем xz -8, пресет с низким значением CompCPU (например, 1) можно изменить, чтобы использовать больший словарь: xz --lzma2=preset=1,dict=32MiB foo.tar С некоторыми файлами вышеуказанная команда может быть быстрее, чем xz -6, в то же время сжимая значительно лучше. Однако, стоит подчеркнуть, что только некоторые файлы受益 от большого словаря, сохраняя значение CompCPU низким. Самая очевидная ситуация, где большой словарь может сильно помочь, — архив, содержащий очень похожие файлы как минимум по несколько мегабайт каждый. Размер словаря должен быть значительно больше, чем любой отдельный файл, чтобы позволить LZMA2 полностью использовать схожести между последовательными файлами. Если очень высокое использование памяти компрессором и декомпрессором допустимо, и сжимаемый файл как минимум несколько сотен мегабайт, может быть полезно использовать даже больший словарь, чем 64 MiB, который использует xz -9: xz -vv --lzma2=dict=192MiB big_foo.tar Использование -vv (--verbose --verbose), как в примере выше, может быть полезным, чтобы увидеть требования к памяти компрессора и декомпрессора. Помните, что использование словаря больше размера несжатого файла — трата памяти, так что вышеуказанная команда не полезна для маленьких файлов. Иногда время сжатия не имеет значения, но использование памяти декомпрессором должно быть сохранено низким, например, чтобы сделать возможным распаковку файла на встроенной системе. Следующая команда использует -6e (-6 --extreme) как базу и устанавливает словарь только в 64 KiB. Получившийся файл можно распаковать с XZ Embedded (вот почему там --check=crc32), используя около 100 KiB памяти. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo Если вы хотите выжать как можно больше байт, корректировка количества бит контекста литералов (lc) и количества бит позиции (pb) иногда помогает. Корректировка количества бит позиции литералов (lp) может помочь тоже, но обычно lc и pb важнее. Например, архив исходного кода содержит в основном текст US-ASCII, так что что-то вроде следующего может дать немного (как 0.1 %) меньший файл, чем xz -6e (попробуйте также без lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Использование другого фильтра вместе с LZMA2 может улучшить сжатие для определенных типов файлов. Например, чтобы сжать общую библиотеку x86-32 или x86-64 с фильтром BCJ x86: xz --x86 --lzma2 libfoo.so Обратите внимание, что порядок опций фильтров значим. Если --x86 указан после --lzma2, xz выдаст ошибку, потому что после LZMA2 не может быть никакого фильтра, и также потому, что фильтр BCJ x86 не может быть использован как последний фильтр в цепочке. Фильтр Delta вместе с LZMA2 может дать хорошие результаты с растровыми изображениями. Он обычно должен превзойти PNG, который имеет несколько более продвинутых фильтров, чем простой дельта, но использует Deflate для фактического сжатия. Изображение должно быть сохранено в несжатом формате, например, как несжатый TIFF. Параметр distance фильтра Delta устанавливается так, чтобы соответствовать количеству байт на пиксель в изображении. Например, 24-битное растровое изображение RGB нуждается в dist=3, и также хорошо передать pb=0 в LZMA2, чтобы учесть трехбайтное выравнивание: xz --delta=dist=3 --lzma2=pb=0 foo.tiff Если несколько изображений помещены в один архив (например, .tar), фильтр Delta будет работать и на нем, пока все изображения имеют одинаковое количество байт на пиксель. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html>
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Compress or decompress .xz and .lzma files SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz is equivalent to xz --decompress. xzcat is equivalent to xz --decompress --stdout. lzma is equivalent to xz --format=lzma. unlzma is equivalent to xz --format=lzma --decompress. lzcat is equivalent to xz --format=lzma --decompress --stdout. When writing scripts that need to decompress files, it is recommended to always use the name xz with appropriate arguments (xz -d or xz -dc) instead of the names unxz and xzcat. DESCRIPTION xz is a general-purpose data compression tool with command line syntax similar to gzip(1) and bzip2(1). The native file format is the .xz format, but the legacy .lzma format used by LZMA Utils and raw com‐ pressed streams with no container format headers are also supported. In addition, decompression of the .lz format used by lzip is supported. xz compresses or decompresses each file according to the selected oper‐ ation mode. If no files are given or file is -, xz reads from standard input and writes the processed data to standard output. xz will refuse (display an error and skip the file) to write compressed data to stan‐ dard output if it is a terminal. Similarly, xz will refuse to read compressed data from standard input if it is a terminal. Unless --stdout is specified, files other than - are written to a new file whose name is derived from the source file name: • When compressing, the suffix of the target file format (.xz or .lzma) is appended to the source filename to get the target file‐ name. • When decompressing, the .xz, .lzma, or .lz suffix is removed from the filename to get the target filename. xz also recognizes the suffixes .txz and .tlz, and replaces them with the .tar suffix. If the target file already exists, an error is displayed and the file is skipped. Unless writing to standard output, xz will display a warning and skip the file if any of the following applies: • File is not a regular file. Symbolic links are not followed, and thus they are not considered to be regular files. • File has more than one hard link. • File has setuid, setgid, or sticky bit set. • The operation mode is set to compress and the file already has a suffix of the target file format (.xz or .txz when compressing to the .xz format, and .lzma or .tlz when compressing to the .lzma for‐ mat). • The operation mode is set to decompress and the file doesn't have a suffix of any of the supported file formats (.xz, .txz, .lzma, .tlz, or .lz). After successfully compressing or decompressing the file, xz copies the owner, group, permissions, access time, and modification time from the source file to the target file. If copying the group fails, the per‐ missions are modified so that the target file doesn't become accessible to users who didn't have permission to access the source file. xz doesn't support copying other metadata like access control lists or ex‐ tended attributes yet. Once the target file has been successfully closed, the source file is removed unless --keep was specified. The source file is never removed if the output is written to standard output or if an error occurs. Sending SIGINFO or SIGUSR1 to the xz process makes it print progress information to standard error. This has only limited use since when standard error is a terminal, using --verbose will display an automati‐ cally updating progress indicator. Memory usage The memory usage of xz varies from a few hundred kilobytes to several gigabytes depending on the compression settings. The settings used when compressing a file determine the memory requirements of the decom‐ pressor. Typically the decompressor needs 5 % to 20 % of the amount of memory that the compressor needed when creating the file. For example, decompressing a file created with xz -9 currently requires 65 MiB of memory. Still, it is possible to have .xz files that require several gigabytes of memory to decompress. Especially users of older systems may find the possibility of very large memory usage annoying. To prevent uncomfortable surprises, xz has a built-in memory usage limiter, which is disabled by default. While some operating systems provide ways to limit the memory usage of processes, relying on it wasn't deemed to be flexible enough (for exam‐ ple, using ulimit(1) to limit virtual memory tends to cripple mmap(2)). The memory usage limiter can be enabled with the command line option --memlimit=limit. Often it is more convenient to enable the limiter by default by setting the environment variable XZ_DEFAULTS, for example, XZ_DEFAULTS=--memlimit=150MiB. It is possible to set the limits sepa‐ rately for compression and decompression by using --memlimit-com‐ press=limit and --memlimit-decompress=limit. Using these two options outside XZ_DEFAULTS is rarely useful because a single run of xz cannot do both compression and decompression and --memlimit=limit (or -M limit) is shorter to type on the command line. If the specified memory usage limit is exceeded when decompressing, xz will display an error and decompressing the file will fail. If the limit is exceeded when compressing, xz will try to scale the settings down so that the limit is no longer exceeded (except when using --for‐ mat=raw or --no-adjust). This way the operation won't fail unless the limit is very small. The scaling of the settings is done in steps that don't match the compression level presets, for example, if the limit is only slightly less than the amount required for xz -9, the settings will be scaled down only a little, not all the way down to xz -8. Concatenation and padding with .xz files It is possible to concatenate .xz files as is. xz will decompress such files as if they were a single .xz file. It is possible to insert padding between the concatenated parts or af‐ ter the last part. The padding must consist of null bytes and the size of the padding must be a multiple of four bytes. This can be useful, for example, if the .xz file is stored on a medium that measures file sizes in 512-byte blocks. Concatenation and padding are not allowed with .lzma files or raw streams. OPTIONS Integer suffixes and special values In most places where an integer argument is expected, an optional suf‐ fix is supported to easily indicate large integers. There must be no space between the integer and the suffix. KiB Multiply the integer by 1,024 (2^10). Ki, k, kB, K, and KB are accepted as synonyms for KiB. MiB Multiply the integer by 1,048,576 (2^20). Mi, m, M, and MB are accepted as synonyms for MiB. GiB Multiply the integer by 1,073,741,824 (2^30). Gi, g, G, and GB are accepted as synonyms for GiB. The special value max can be used to indicate the maximum integer value supported by the option. Operation mode If multiple operation mode options are given, the last one takes ef‐ fect. -z, --compress Compress. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, unxz implies --decompress). After successful compression, the source file is removed unless writing to standard output or --keep was specified. -d, --decompress, --uncompress Decompress. After successful decompression, the source file is removed unless writing to standard output or --keep was speci‐ fied. -t, --test Test the integrity of compressed files. This option is equiva‐ lent to --decompress --stdout except that the decompressed data is discarded instead of being written to standard output. No files are created or removed. -l, --list Print information about compressed files. No uncompressed out‐ put is produced, and no files are created or removed. In list mode, the program cannot read the compressed data from standard input or from other unseekable sources. The default listing shows basic information about files, one file per line. To get more detailed information, use also the --verbose option. For even more information, use --verbose twice, but note that this may be slow, because getting all the extra information requires many seeks. The width of verbose output exceeds 80 characters, so piping the output to, for exam‐ ple, less -S may be convenient if the terminal isn't wide enough. The exact output may vary between xz versions and different lo‐ cales. For machine-readable output, --robot --list should be used. Operation modifiers -k, --keep Don't delete the input files. Since xz 5.2.6, this option also makes xz compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. In earlier versions this was only done with --force. -f, --force This option has several effects: • If the target file already exists, delete it before compress‐ ing or decompressing. • Compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. • When used with --decompress --stdout and xz cannot recognize the type of the source file, copy the source file as is to standard output. This allows xzcat --force to be used like cat(1) for files that have not been compressed with xz. Note that in future, xz might support new compressed file formats, which may make xz decompress more types of files instead of copying them as is to standard output. --format=format can be used to restrict xz to decompress only a single file for‐ mat. -c, --stdout, --to-stdout Write the compressed or decompressed data to standard output in‐ stead of a file. This implies --keep. --single-stream Decompress only the first .xz stream, and silently ignore possi‐ ble remaining input data following the stream. Normally such trailing garbage makes xz display an error. xz never decompresses more than one stream from .lzma files or raw streams, but this option still makes xz ignore the possible trailing data after the .lzma file or raw stream. This option has no effect if the operation mode is not --decom‐ press or --test. --no-sparse Disable creation of sparse files. By default, if decompressing into a regular file, xz tries to make the file sparse if the de‐ compressed data contains long sequences of binary zeros. It also works when writing to standard output as long as standard output is connected to a regular file and certain additional conditions are met to make it safe. Creating sparse files may save disk space and speed up the decompression by reducing the amount of disk I/O. -S .suf, --suffix=.suf When compressing, use .suf as the suffix for the target file in‐ stead of .xz or .lzma. If not writing to standard output and the source file already has the suffix .suf, a warning is dis‐ played and the file is skipped. When decompressing, recognize files with the suffix .suf in ad‐ dition to files with the .xz, .txz, .lzma, .tlz, or .lz suffix. If the source file has the suffix .suf, the suffix is removed to get the target filename. When compressing or decompressing raw streams (--format=raw), the suffix must always be specified unless writing to standard output, because there is no default suffix for raw streams. --files[=file] Read the filenames to process from file; if file is omitted, filenames are read from standard input. Filenames must be ter‐ minated with the newline character. A dash (-) is taken as a regular filename; it doesn't mean standard input. If filenames are given also as command line arguments, they are processed be‐ fore the filenames read from file. --files0[=file] This is identical to --files[=file] except that each filename must be terminated with the null character. Basic file format and compression options -F format, --format=format Specify the file format to compress or decompress: auto This is the default. When compressing, auto is equiva‐ lent to xz. When decompressing, the format of the input file is automatically detected. Note that raw streams (created with --format=raw) cannot be auto-detected. xz Compress to the .xz file format, or accept only .xz files when decompressing. lzma, alone Compress to the legacy .lzma file format, or accept only .lzma files when decompressing. The alternative name alone is provided for backwards compatibility with LZMA Utils. lzip Accept only .lz files when decompressing. Compression is not supported. The .lz format version 0 and the unextended version 1 are supported. Version 0 files were produced by lzip 1.3 and older. Such files aren't common but may be found from file archives as a few source packages were released in this format. People might have old personal files in this format too. Decompression support for the format version 0 was removed in lzip 1.18. lzip 1.4 and later create files in the format version 1. The sync flush marker extension to the format version 1 was added in lzip 1.6. This extension is rarely used and isn't supported by xz (diagnosed as corrupt input). raw Compress or uncompress a raw stream (no headers). This is meant for advanced users only. To decode raw streams, you need use --format=raw and explicitly specify the fil‐ ter chain, which normally would have been stored in the container headers. -C check, --check=check Specify the type of the integrity check. The check is calcu‐ lated from the uncompressed data and stored in the .xz file. This option has an effect only when compressing into the .xz format; the .lzma format doesn't support integrity checks. The integrity check (if any) is verified when the .xz file is decom‐ pressed. Supported check types: none Don't calculate an integrity check at all. This is usu‐ ally a bad idea. This can be useful when integrity of the data is verified by other means anyway. crc32 Calculate CRC32 using the polynomial from IEEE-802.3 (Ethernet). crc64 Calculate CRC64 using the polynomial from ECMA-182. This is the default, since it is slightly better than CRC32 at detecting damaged files and the speed difference is neg‐ ligible. sha256 Calculate SHA-256. This is somewhat slower than CRC32 and CRC64. Integrity of the .xz headers is always verified with CRC32. It is not possible to change or disable it. --ignore-check Don't verify the integrity check of the compressed data when de‐ compressing. The CRC32 values in the .xz headers will still be verified normally. Do not use this option unless you know what you are doing. Pos‐ sible reasons to use this option: • Trying to recover data from a corrupt .xz file. • Speeding up decompression. This matters mostly with SHA-256 or with files that have compressed extremely well. It's rec‐ ommended to not use this option for this purpose unless the file integrity is verified externally in some other way. -0 ... -9 Select a compression preset level. The default is -6. If mul‐ tiple preset levels are specified, the last one takes effect. If a custom filter chain was already specified, setting a com‐ pression preset level clears the custom filter chain. The differences between the presets are more significant than with gzip(1) and bzip2(1). The selected compression settings determine the memory requirements of the decompressor, thus us‐ ing a too high preset level might make it painful to decompress the file on an old system with little RAM. Specifically, it's not a good idea to blindly use -9 for everything like it often is with gzip(1) and bzip2(1). -0 ... -3 These are somewhat fast presets. -0 is sometimes faster than gzip -9 while compressing much better. The higher ones often have speed comparable to bzip2(1) with compa‐ rable or better compression ratio, although the results depend a lot on the type of data being compressed. -4 ... -6 Good to very good compression while keeping decompressor memory usage reasonable even for old systems. -6 is the default, which is usually a good choice for distributing files that need to be decompressible even on systems with only 16 MiB RAM. (-5e or -6e may be worth considering too. See --extreme.) -7 ... -9 These are like -6 but with higher compressor and decom‐ pressor memory requirements. These are useful only when compressing files bigger than 8 MiB, 16 MiB, and 32 MiB, respectively. On the same hardware, the decompression speed is approximately a constant number of bytes of compressed data per second. In other words, the better the compression, the faster the decom‐ pression will usually be. This also means that the amount of uncompressed output produced per second can vary a lot. The following table summarises the features of the presets: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Column descriptions: • DictSize is the LZMA2 dictionary size. It is waste of memory to use a dictionary bigger than the size of the uncompressed file. This is why it is good to avoid using the presets -7 ... -9 when there's no real need for them. At -6 and lower, the amount of memory wasted is usually low enough to not mat‐ ter. • CompCPU is a simplified representation of the LZMA2 settings that affect compression speed. The dictionary size affects speed too, so while CompCPU is the same for levels -6 ... -9, higher levels still tend to be a little slower. To get even slower and thus possibly better compression, see --extreme. • CompMem contains the compressor memory requirements in the single-threaded mode. It may vary slightly between xz ver‐ sions. • DecMem contains the decompressor memory requirements. That is, the compression settings determine the memory require‐ ments of the decompressor. The exact decompressor memory us‐ age is slightly more than the LZMA2 dictionary size, but the values in the table have been rounded up to the next full MiB. Memory requirements of the multi-threaded mode are significantly higher than that of the single-threaded mode. With the default value of --block-size, each thread needs 3*3*DictSize plus Comp‐ Mem or DecMem. For example, four threads with preset -6 needs 660–670 MiB of memory. -e, --extreme Use a slower variant of the selected compression preset level (-0 ... -9) to hopefully get a little bit better compression ra‐ tio, but with bad luck this can also make it worse. Decompres‐ sor memory usage is not affected, but compressor memory usage increases a little at preset levels -0 ... -3. Since there are two presets with dictionary sizes 4 MiB and 8 MiB, the presets -3e and -5e use slightly faster settings (lower CompCPU) than -4e and -6e, respectively. That way no two presets are identical. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB For example, there are a total of four presets that use 8 MiB dictionary, whose order from the fastest to the slowest is -5, -6, -5e, and -6e. --fast --best These are somewhat misleading aliases for -0 and -9, respec‐ tively. These are provided only for backwards compatibility with LZMA Utils. Avoid using these options. --block-size=size When compressing to the .xz format, split the input data into blocks of size bytes. The blocks are compressed independently from each other, which helps with multi-threading and makes lim‐ ited random-access decompression possible. This option is typi‐ cally used to override the default block size in multi-threaded mode, but this option can be used in single-threaded mode too. In multi-threaded mode about three times size bytes will be al‐ located in each thread for buffering input and output. The de‐ fault size is three times the LZMA2 dictionary size or 1 MiB, whichever is more. Typically a good value is 2–4 times the size of the LZMA2 dictionary or at least 1 MiB. Using size less than the LZMA2 dictionary size is waste of RAM because then the LZMA2 dictionary buffer will never get fully used. In multi-threaded mode, the sizes of the blocks are stored in the block headers. This size information is required for multi-threaded decompres‐ sion. In single-threaded mode no block splitting is done by default. Setting this option doesn't affect memory usage. No size infor‐ mation is stored in block headers, thus files created in single- threaded mode won't be identical to files created in multi- threaded mode. The lack of size information also means that xz won't be able decompress the files in multi-threaded mode. --block-list=items When compressing to the .xz format, start a new block with an optional custom filter chain after the given intervals of uncom‐ pressed data. The items are a comma-separated list. Each item consists of an optional filter chain number between 0 and 9 followed by a colon (:) and a required size of uncompressed data. Omitting an item (two or more consecutive commas) is a shorthand to use the size and filters of the previous item. If the input file is bigger than the sum of the sizes in items, the last item is repeated until the end of the file. A special value of 0 may be used as the last size to indicate that the rest of the file should be encoded as a single block. An alternative filter chain for each block can be specified in combination with the --filters1=filters ... --filters9=filters options. These options define filter chains with an identifier between 1–9. Filter chain 0 can be used to refer to the default filter chain, which is the same as not specifying a filter chain. The filter chain identifier can be used before the un‐ compressed size, followed by a colon (:). For example, if one specifies --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB then blocks will be created using: • The filter chain specified by --filters1 and 2 MiB input • The filter chain specified by --filters3 and 2 MiB input • The filter chain specified by --filters2 and 4 MiB input • The filter chain specified by --filters2 and 4 MiB input • The default filter chain and 2 MiB input • The default filter chain and 4 MiB input for every block un‐ til end of input. If one specifies a size that exceeds the encoder's block size (either the default value in threaded mode or the value speci‐ fied with --block-size=size), the encoder will create additional blocks while keeping the boundaries specified in items. For ex‐ ample, if one specifies --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB and the input file is 80 MiB, one will get 11 blocks: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10, and 1 MiB. In multi-threaded mode the sizes of the blocks are stored in the block headers. This isn't done in single-threaded mode, so the encoded output won't be identical to that of the multi-threaded mode. --flush-timeout=timeout When compressing, if more than timeout milliseconds (a positive integer) has passed since the previous flush and reading more input would block, all the pending input data is flushed from the encoder and made available in the output stream. This can be useful if xz is used to compress data that is streamed over a network. Small timeout values make the data available at the receiving end with a small delay, but large timeout values give better compression ratio. This feature is disabled by default. If this option is speci‐ fied more than once, the last one takes effect. The special timeout value of 0 can be used to explicitly disable this fea‐ ture. This feature is not available on non-POSIX systems. This feature is still experimental. Currently xz is unsuitable for decompressing the stream in real time due to how xz does buffering. --memlimit-compress=limit Set a memory usage limit for compression. If this option is specified multiple times, the last one takes effect. If the compression settings exceed the limit, xz will attempt to adjust the settings downwards so that the limit is no longer ex‐ ceeded and display a notice that automatic adjustment was done. The adjustments are done in this order: reducing the number of threads, switching to single-threaded mode if even one thread in multi-threaded mode exceeds the limit, and finally reducing the LZMA2 dictionary size. When compressing with --format=raw or if --no-adjust has been specified, only the number of threads may be reduced since it can be done without affecting the compressed output. If the limit cannot be met even with the adjustments described above, an error is displayed and xz will exit with exit status 1. The limit can be specified in multiple ways: • The limit can be an absolute value in bytes. Using an inte‐ ger suffix like MiB can be useful. Example: --memlimit-com‐ press=80MiB • The limit can be specified as a percentage of total physical memory (RAM). This can be useful especially when setting the XZ_DEFAULTS environment variable in a shell initialization script that is shared between different computers. That way the limit is automatically bigger on systems with more mem‐ ory. Example: --memlimit-compress=70% • The limit can be reset back to its default value by setting it to 0. This is currently equivalent to setting the limit to max (no memory usage limit). For 32-bit xz there is a special case: if the limit would be over 4020 MiB, the limit is set to 4020 MiB. On MIPS32 2000 MiB is used instead. (The values 0 and max aren't affected by this. A similar feature doesn't exist for decompression.) This can be helpful when a 32-bit executable has access to 4 GiB address space (2 GiB on MIPS32) while hopefully doing no harm in other situations. See also the section Memory usage. --memlimit-decompress=limit Set a memory usage limit for decompression. This also affects the --list mode. If the operation is not possible without ex‐ ceeding the limit, xz will display an error and decompressing the file will fail. See --memlimit-compress=limit for possible ways to specify the limit. --memlimit-mt-decompress=limit Set a memory usage limit for multi-threaded decompression. This can only affect the number of threads; this will never make xz refuse to decompress a file. If limit is too low to allow any multi-threading, the limit is ignored and xz will continue in single-threaded mode. Note that if also --memlimit-decompress is used, it will always apply to both single-threaded and multi- threaded modes, and so the effective limit for multi-threading will never be higher than the limit set with --memlimit-decom‐ press. In contrast to the other memory usage limit options, --mem‐ limit-mt-decompress=limit has a system-specific default limit. xz --info-memory can be used to see the current value. This option and its default value exist because without any limit the threaded decompressor could end up allocating an in‐ sane amount of memory with some input files. If the default limit is too low on your system, feel free to increase the limit but never set it to a value larger than the amount of usable RAM as with appropriate input files xz will attempt to use that amount of memory even with a low number of threads. Running out of memory or swapping will not improve decompression perfor‐ mance. See --memlimit-compress=limit for possible ways to specify the limit. Setting limit to 0 resets the limit to the default sys‐ tem-specific value. -M limit, --memlimit=limit, --memory=limit This is equivalent to specifying --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Display an error and exit if the memory usage limit cannot be met without adjusting settings that affect the compressed out‐ put. That is, this prevents xz from switching the encoder from multi-threaded mode to single-threaded mode and from reducing the LZMA2 dictionary size. Even when this option is used the number of threads may be reduced to meet the memory usage limit as that won't affect the compressed output. Automatic adjusting is always disabled when creating raw streams (--format=raw). -T threads, --threads=threads Specify the number of worker threads to use. Setting threads to a special value 0 makes xz use up to as many threads as the pro‐ cessor(s) on the system support. The actual number of threads can be fewer than threads if the input file is not big enough for threading with the given settings or if using more threads would exceed the memory usage limit. The single-threaded and multi-threaded compressors produce dif‐ ferent output. Single-threaded compressor will give the small‐ est file size but only the output from the multi-threaded com‐ pressor can be decompressed using multiple threads. Setting threads to 1 will use the single-threaded mode. Setting threads to any other value, including 0, will use the multi-threaded compressor even if the system supports only one hardware thread. (xz 5.2.x used single-threaded mode in this situation.) To use multi-threaded mode with only one thread, set threads to +1. The + prefix has no effect with values other than 1. A memory usage limit can still make xz switch to single-threaded mode unless --no-adjust is used. Support for the + prefix was added in xz 5.4.0. If an automatic number of threads has been requested and no mem‐ ory usage limit has been specified, then a system-specific de‐ fault soft limit will be used to possibly limit the number of threads. It is a soft limit in sense that it is ignored if the number of threads becomes one, thus a soft limit will never stop xz from compressing or decompressing. This default soft limit will not make xz switch from multi-threaded mode to single- threaded mode. The active limits can be seen with xz --info-memory. Currently the only threading method is to split the input into blocks and compress them independently from each other. The de‐ fault block size depends on the compression level and can be overridden with the --block-size=size option. Threaded decompression only works on files that contain multiple blocks with size information in block headers. All large enough files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size has been used. The default value for threads is 0. In xz 5.4.x and older the default is 1. Custom compressor filter chains A custom filter chain allows specifying the compression settings in de‐ tail instead of relying on the settings associated to the presets. When a custom filter chain is specified, preset options (-0 ... -9 and --extreme) earlier on the command line are forgotten. If a preset op‐ tion is specified after one or more custom filter chain options, the new preset takes effect and the custom filter chain options specified earlier are forgotten. A filter chain is comparable to piping on the command line. When com‐ pressing, the uncompressed input goes to the first filter, whose output goes to the next filter (if any). The output of the last filter gets written to the compressed file. The maximum number of filters in the chain is four, but typically a filter chain has only one or two fil‐ ters. Many filters have limitations on where they can be in the filter chain: some filters can work only as the last filter in the chain, some only as a non-last filter, and some work in any position in the chain. De‐ pending on the filter, this limitation is either inherent to the filter design or exists to prevent security issues. A custom filter chain can be specified in two different ways. The op‐ tions --filters=filters and --filters1=filters ... --filters9=filters allow specifying an entire filter chain in one option using the liblzma filter string syntax. Alternatively, a filter chain can be specified by using one or more individual filter options in the order they are wanted in the filter chain. That is, the order of the individual fil‐ ter options is significant! When decoding raw streams (--format=raw), the filter chain must be specified in the same order as it was speci‐ fied when compressing. Any individual filter or preset options speci‐ fied before the full chain option (--filters=filters) will be forgot‐ ten. Individual filters specified after the full chain option will re‐ set the filter chain. Both the full and individual filter options take filter-specific op‐ tions as a comma-separated list. Extra commas in options are ignored. Every option has a default value, so specify those you want to change. To see the whole filter chain and options, use xz -vv (that is, use --verbose twice). This works also for viewing the filter chain options used by presets. --filters=filters Specify the full filter chain or a preset in a single option. Each filter can be separated by spaces or two dashes (--). fil‐ ters may need to be quoted on the shell command line so it is parsed as a single option. To denote options, use : or =. A preset can be prefixed with a - and followed with zero or more flags. The only supported flag is e to apply the same options as --extreme. --filters1=filters ... --filters9=filters Specify up to nine additional filter chains that can be used with --block-list. For example, when compressing an archive with executable files followed by text files, the executable part could use a filter chain with a BCJ filter and the text part only the LZMA2 filter. --filters-help Display a help message describing how to specify presets and custom filter chains in the --filters and --filters1=filters ... --filters9=filters options, and exit successfully. --lzma1[=options] --lzma2[=options] Add LZMA1 or LZMA2 filter to the filter chain. These filters can be used only as the last filter in the chain. LZMA1 is a legacy filter, which is supported almost solely due to the legacy .lzma file format, which supports only LZMA1. LZMA2 is an updated version of LZMA1 to fix some practical is‐ sues of LZMA1. The .xz format uses LZMA2 and doesn't support LZMA1 at all. Compression speed and ratios of LZMA1 and LZMA2 are practically the same. LZMA1 and LZMA2 share the same set of options: preset=preset Reset all LZMA1 or LZMA2 options to preset. Preset con‐ sist of an integer, which may be followed by single-let‐ ter preset modifiers. The integer can be from 0 to 9, matching the command line options -0 ... -9. The only supported modifier is currently e, which matches --ex‐ treme. If no preset is specified, the default values of LZMA1 or LZMA2 options are taken from the preset 6. dict=size Dictionary (history buffer) size indicates how many bytes of the recently processed uncompressed data is kept in memory. The algorithm tries to find repeating byte se‐ quences (matches) in the uncompressed data, and replace them with references to the data currently in the dictio‐ nary. The bigger the dictionary, the higher is the chance to find a match. Thus, increasing dictionary size usually improves compression ratio, but a dictionary big‐ ger than the uncompressed file is waste of memory. Typical dictionary size is from 64 KiB to 64 MiB. The minimum is 4 KiB. The maximum for compression is cur‐ rently 1.5 GiB (1536 MiB). The decompressor already sup‐ ports dictionaries up to one byte less than 4 GiB, which is the maximum for the LZMA1 and LZMA2 stream formats. Dictionary size and match finder (mf) together determine the memory usage of the LZMA1 or LZMA2 encoder. The same (or bigger) dictionary size is required for decompressing that was used when compressing, thus the memory usage of the decoder is determined by the dictionary size used when compressing. The .xz headers store the dictionary size either as 2^n or 2^n + 2^(n-1), so these sizes are somewhat preferred for compression. Other sizes will get rounded up when stored in the .xz headers. lc=lc Specify the number of literal context bits. The minimum is 0 and the maximum is 4; the default is 3. In addi‐ tion, the sum of lc and lp must not exceed 4. All bytes that cannot be encoded as matches are encoded as literals. That is, literals are simply 8-bit bytes that are encoded one at a time. The literal coding makes an assumption that the highest lc bits of the previous uncompressed byte correlate with the next byte. For example, in typical English text, an upper-case letter is often followed by a lower-case let‐ ter, and a lower-case letter is usually followed by an‐ other lower-case letter. In the US-ASCII character set, the highest three bits are 010 for upper-case letters and 011 for lower-case letters. When lc is at least 3, the literal coding can take advantage of this property in the uncompressed data. The default value (3) is usually good. If you want maxi‐ mum compression, test lc=4. Sometimes it helps a little, and sometimes it makes compression worse. If it makes it worse, test lc=2 too. lp=lp Specify the number of literal position bits. The minimum is 0 and the maximum is 4; the default is 0. Lp affects what kind of alignment in the uncompressed data is assumed when encoding literals. See pb below for more information about alignment. pb=pb Specify the number of position bits. The minimum is 0 and the maximum is 4; the default is 2. Pb affects what kind of alignment in the uncompressed data is assumed in general. The default means four-byte alignment (2^pb=2^2=4), which is often a good choice when there's no better guess. When the alignment is known, setting pb accordingly may reduce the file size a little. For example, with text files having one-byte alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can improve compression slightly. For UTF-16 text, pb=1 is a good choice. If the alignment is an odd number like 3 bytes, pb=0 might be the best choice. Even though the assumed alignment can be adjusted with pb and lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment. It might be worth taking into account when designing file formats that are likely to be often com‐ pressed with LZMA1 or LZMA2. mf=mf Match finder has a major effect on encoder speed, memory usage, and compression ratio. Usually Hash Chain match finders are faster than Binary Tree match finders. The default depends on the preset: 0 uses hc3, 1–3 use hc4, and the rest use bt4. The following match finders are supported. The memory usage formulas below are rough approximations, which are closest to the reality when dict is a power of two. hc3 Hash Chain with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 7.5 (if dict <= 16 MiB); dict * 5.5 + 64 MiB (if dict > 16 MiB) hc4 Hash Chain with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 7.5 (if dict <= 32 MiB); dict * 6.5 (if dict > 32 MiB) bt2 Binary Tree with 2-byte hashing Minimum value for nice: 2 Memory usage: dict * 9.5 bt3 Binary Tree with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 11.5 (if dict <= 16 MiB); dict * 9.5 + 64 MiB (if dict > 16 MiB) bt4 Binary Tree with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 11.5 (if dict <= 32 MiB); dict * 10.5 (if dict > 32 MiB) mode=mode Compression mode specifies the method to analyze the data produced by the match finder. Supported modes are fast and normal. The default is fast for presets 0–3 and nor‐ mal for presets 4–9. Usually fast is used with Hash Chain match finders and normal with Binary Tree match finders. This is also what the presets do. nice=nice Specify what is considered to be a nice length for a match. Once a match of at least nice bytes is found, the algorithm stops looking for possibly better matches. Nice can be 2–273 bytes. Higher values tend to give bet‐ ter compression ratio at the expense of speed. The de‐ fault depends on the preset. depth=depth Specify the maximum search depth in the match finder. The default is the special value of 0, which makes the compressor determine a reasonable depth from mf and nice. Reasonable depth for Hash Chains is 4–100 and 16–1000 for Binary Trees. Using very high values for depth can make the encoder extremely slow with some files. Avoid set‐ ting the depth over 1000 unless you are prepared to in‐ terrupt the compression in case it is taking far too long. When decoding raw streams (--format=raw), LZMA2 needs only the dictionary size. LZMA1 needs also lc, lp, and pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Add a branch/call/jump (BCJ) filter to the filter chain. These filters can be used only as a non-last filter in the filter chain. A BCJ filter converts relative addresses in the machine code to their absolute counterparts. This doesn't change the size of the data but it increases redundancy, which can help LZMA2 to produce 0–15 % smaller .xz file. The BCJ filters are always re‐ versible, so using a BCJ filter for wrong type of data doesn't cause any data loss, although it may make the compression ratio slightly worse. The BCJ filters are very fast and use an in‐ significant amount of memory. These BCJ filters have known problems related to the compression ratio: • Some types of files containing executable code (for example, object files, static libraries, and Linux kernel modules) have the addresses in the instructions filled with filler values. These BCJ filters will still do the address conver‐ sion, which will make the compression worse with these files. • If a BCJ filter is applied on an archive, it is possible that it makes the compression ratio worse than not using a BCJ filter. For example, if there are similar or even identical executables then filtering will likely make the files less similar and thus compression is worse. The contents of non- executable files in the same archive can matter too. In practice one has to try with and without a BCJ filter to see which is better in each situation. Different instruction sets have different alignment: the exe‐ cutable file must be aligned to a multiple of this value in the input data to make the filter work. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit or 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Since the BCJ-filtered data is usually compressed with LZMA2, the compression ratio may be improved slightly if the LZMA2 op‐ tions are set to match the alignment of the selected BCJ filter. Examples: • IA-64 filter has 16-byte alignment so pb=4,lp=4,lc=0 is good with LZMA2 (2^4=16). • RISC-V code has 2-byte or 4-byte alignment depending on whether the file contains 16-bit compressed instructions (the C extension). When 16-bit instructions are used, pb=2,lp=1,lc=3 or pb=1,lp=1,lc=3 is good. When 16-bit in‐ structions aren't present, pb=2,lp=2,lc=2 is the best. read‐ elf -h can be used to check if "RVC" appears on the "Flags" line. • ARM64 is always 4-byte aligned so pb=2,lp=2,lc=2 is the best. • The x86 filter is an exception. It's usually good to stick to LZMA2's defaults (pb=2,lp=0,lc=3) when compressing x86 ex‐ ecutables. All BCJ filters support the same options: start=offset Specify the start offset that is used when converting be‐ tween relative and absolute addresses. The offset must be a multiple of the alignment of the filter (see the ta‐ ble above). The default is zero. In practice, the de‐ fault is good; specifying a custom offset is almost never useful. --delta[=options] Add the Delta filter to the filter chain. The Delta filter can be only used as a non-last filter in the filter chain. Currently only simple byte-wise delta calculation is supported. It can be useful when compressing, for example, uncompressed bitmap images or uncompressed PCM audio. However, special pur‐ pose algorithms may give significantly better results than Delta + LZMA2. This is true especially with audio, which compresses faster and better, for example, with flac(1). Supported options: dist=distance Specify the distance of the delta calculation in bytes. distance must be 1–256. The default is 1. For example, with dist=2 and eight-byte input A1 B1 A2 B3 A3 B5 A4 B7, the output will be A1 B1 01 02 01 02 01 02. Other options -q, --quiet Suppress warnings and notices. Specify this twice to suppress errors too. This option has no effect on the exit status. That is, even if a warning was suppressed, the exit status to indi‐ cate a warning is still used. -v, --verbose Be verbose. If standard error is connected to a terminal, xz will display a progress indicator. Specifying --verbose twice will give even more verbose output. The progress indicator shows the following information: • Completion percentage is shown if the size of the input file is known. That is, the percentage cannot be shown in pipes. • Amount of compressed data produced (compressing) or consumed (decompressing). • Amount of uncompressed data consumed (compressing) or pro‐ duced (decompressing). • Compression ratio, which is calculated by dividing the amount of compressed data processed so far by the amount of uncom‐ pressed data processed so far. • Compression or decompression speed. This is measured as the amount of uncompressed data consumed (compression) or pro‐ duced (decompression) per second. It is shown after a few seconds have passed since xz started processing the file. • Elapsed time in the format M:SS or H:MM:SS. • Estimated remaining time is shown only when the size of the input file is known and a couple of seconds have already passed since xz started processing the file. The time is shown in a less precise format which never has any colons, for example, 2 min 30 s. When standard error is not a terminal, --verbose will make xz print the filename, compressed size, uncompressed size, compres‐ sion ratio, and possibly also the speed and elapsed time on a single line to standard error after compressing or decompressing the file. The speed and elapsed time are included only when the operation took at least a few seconds. If the operation didn't finish, for example, due to user interruption, also the comple‐ tion percentage is printed if the size of the input file is known. -Q, --no-warn Don't set the exit status to 2 even if a condition worth a warn‐ ing was detected. This option doesn't affect the verbosity level, thus both --quiet and --no-warn have to be used to not display warnings and to not alter the exit status. --robot Print messages in a machine-parsable format. This is intended to ease writing frontends that want to use xz instead of li‐ blzma, which may be the case with various scripts. The output with this option enabled is meant to be stable across xz re‐ leases. See the section ROBOT MODE for details. --info-memory Display, in human-readable format, how much physical memory (RAM) and how many processor threads xz thinks the system has and the memory usage limits for compression and decompression, and exit successfully. -h, --help Display a help message describing the most commonly used op‐ tions, and exit successfully. -H, --long-help Display a help message describing all features of xz, and exit successfully -V, --version Display the version number of xz and liblzma in human readable format. To get machine-parsable output, specify --robot before --version. ROBOT MODE The robot mode is activated with the --robot option. It makes the out‐ put of xz easier to parse by other programs. Currently --robot is sup‐ ported only together with --list, --filters-help, --info-memory, and --version. It will be supported for compression and decompression in the future. List mode xz --robot --list uses tab-separated output. The first column of every line has a string that indicates the type of the information found on that line: name This is always the first line when starting to list a file. The second column on the line is the filename. file This line contains overall information about the .xz file. This line is always printed after the name line. stream This line type is used only when --verbose was specified. There are as many stream lines as there are streams in the .xz file. block This line type is used only when --verbose was specified. There are as many block lines as there are blocks in the .xz file. The block lines are shown after all the stream lines; different line types are not interleaved. summary This line type is used only when --verbose was specified twice. This line is printed after all block lines. Like the file line, the summary line contains overall information about the .xz file. totals This line is always the very last line of the list output. It shows the total counts and sizes. The columns of the file lines: 2. Number of streams in the file 3. Total number of blocks in the stream(s) 4. Compressed size of the file 5. Uncompressed size of the file 6. Compression ratio, for example, 0.123. If ratio is over 9.999, three dashes (---) are displayed instead of the ra‐ tio. 7. Comma-separated list of integrity check names. The follow‐ ing strings are used for the known check types: None, CRC32, CRC64, and SHA-256. For unknown check types, Unknown-N is used, where N is the Check ID as a decimal number (one or two digits). 8. Total size of stream padding in the file The columns of the stream lines: 2. Stream number (the first stream is 1) 3. Number of blocks in the stream 4. Compressed start offset 5. Uncompressed start offset 6. Compressed size (does not include stream padding) 7. Uncompressed size 8. Compression ratio 9. Name of the integrity check 10. Size of stream padding The columns of the block lines: 2. Number of the stream containing this block 3. Block number relative to the beginning of the stream (the first block is 1) 4. Block number relative to the beginning of the file 5. Compressed start offset relative to the beginning of the file 6. Uncompressed start offset relative to the beginning of the file 7. Total compressed size of the block (includes headers) 8. Uncompressed size 9. Compression ratio 10. Name of the integrity check If --verbose was specified twice, additional columns are included on the block lines. These are not displayed with a single --verbose, be‐ cause getting this information requires many seeks and can thus be slow: 11. Value of the integrity check in hexadecimal 12. Block header size 13. Block flags: c indicates that compressed size is present, and u indicates that uncompressed size is present. If the flag is not set, a dash (-) is shown instead to keep the string length fixed. New flags may be added to the end of the string in the future. 14. Size of the actual compressed data in the block (this ex‐ cludes the block header, block padding, and check fields) 15. Amount of memory (in bytes) required to decompress this block with this xz version 16. Filter chain. Note that most of the options used at com‐ pression time cannot be known, because only the options that are needed for decompression are stored in the .xz headers. The columns of the summary lines: 2. Amount of memory (in bytes) required to decompress this file with this xz version 3. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 4. Minimum xz version required to decompress the file The columns of the totals line: 2. Number of streams 3. Number of blocks 4. Compressed size 5. Uncompressed size 6. Average compression ratio 7. Comma-separated list of integrity check names that were present in the files 8. Stream padding size 9. Number of files. This is here to keep the order of the ear‐ lier columns the same as on file lines. If --verbose was specified twice, additional columns are included on the totals line: 10. Maximum amount of memory (in bytes) required to decompress the files with this xz version 11. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 12. Minimum xz version required to decompress the file Future versions may add new line types and new columns can be added to the existing line types, but the existing columns won't be changed. Filters help xz --robot --filters-help prints the supported filters in the following format: filter:option=<value>,option=<value>... filter Name of the filter option Name of a filter specific option value Numeric value ranges appear as <min-max>. String value choices are shown within < > and separated by a | character. Each filter is printed on its own line. Memory limit information xz --robot --info-memory prints a single line with multiple tab-sepa‐ rated columns: 1. Total amount of physical memory (RAM) in bytes. 2. Memory usage limit for compression in bytes (--memlimit-compress). A special value of 0 indicates the default setting which for sin‐ gle-threaded mode is the same as no limit. 3. Memory usage limit for decompression in bytes (--memlimit-decom‐ press). A special value of 0 indicates the default setting which for single-threaded mode is the same as no limit. 4. Since xz 5.3.4alpha: Memory usage for multi-threaded decompression in bytes (--memlimit-mt-decompress). This is never zero because a system-specific default value shown in the column 5 is used if no limit has been specified explicitly. This is also never greater than the value in the column 3 even if a larger value has been specified with --memlimit-mt-decompress. 5. Since xz 5.3.4alpha: A system-specific default memory usage limit that is used to limit the number of threads when compressing with an automatic number of threads (--threads=0) and no memory usage limit has been specified (--memlimit-compress). This is also used as the default value for --memlimit-mt-decompress. 6. Since xz 5.3.4alpha: Number of available processor threads. In the future, the output of xz --robot --info-memory may have more columns, but never more than a single line. Version xz --robot --version prints the version number of xz and liblzma in the following format: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Major version. YYY Minor version. Even numbers are stable. Odd numbers are alpha or beta versions. ZZZ Patch level for stable releases or just a counter for develop‐ ment releases. S Stability. 0 is alpha, 1 is beta, and 2 is stable. S should be always 2 when YYY is even. XYYYZZZS are the same on both lines if xz and liblzma are from the same XZ Utils release. Examples: 4.999.9beta is 49990091 and 5.0.0 is 50000002. EXIT STATUS 0 All is good. 1 An error occurred. 2 Something worth a warning occurred, but no actual errors oc‐ curred. Notices (not warnings or errors) printed on standard error don't affect the exit status. ENVIRONMENT xz parses space-separated lists of options from the environment vari‐ ables XZ_DEFAULTS and XZ_OPT, in this order, before parsing the options from the command line. Note that only options are parsed from the en‐ vironment variables; all non-options are silently ignored. Parsing is done with getopt_long(3) which is used also for the command line argu‐ ments. XZ_DEFAULTS User-specific or system-wide default options. Typically this is set in a shell initialization script to enable xz's memory usage limiter by default. Excluding shell initialization scripts and similar special cases, scripts must never set or unset XZ_DE‐ FAULTS. XZ_OPT This is for passing options to xz when it is not possible to set the options directly on the xz command line. This is the case when xz is run by a script or tool, for example, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Scripts may use XZ_OPT, for example, to set script-specific de‐ fault compression options. It is still recommended to allow users to override XZ_OPT if that is reasonable. For example, in sh(1) scripts one may use something like this: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY The command line syntax of xz is practically a superset of lzma, un‐ lzma, and lzcat as found from LZMA Utils 4.32.x. In most cases, it is possible to replace LZMA Utils with XZ Utils without breaking existing scripts. There are some incompatibilities though, which may sometimes cause problems. Compression preset levels The numbering of the compression level presets is not identical in xz and LZMA Utils. The most important difference is how dictionary sizes are mapped to different presets. Dictionary size is roughly equal to the decompressor memory usage. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB The dictionary size differences affect the compressor memory usage too, but there are some other differences between LZMA Utils and XZ Utils, which make the difference even bigger: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB The default preset level in LZMA Utils is -7 while in XZ Utils it is -6, so both use an 8 MiB dictionary by default. Streamed vs. non-streamed .lzma files The uncompressed size of the file can be stored in the .lzma header. LZMA Utils does that when compressing regular files. The alternative is to mark that uncompressed size is unknown and use end-of-payload marker to indicate where the decompressor should stop. LZMA Utils uses this method when uncompressed size isn't known, which is the case, for example, in pipes. xz supports decompressing .lzma files with or without end-of-payload marker, but all .lzma files created by xz will use end-of-payload marker and have uncompressed size marked as unknown in the .lzma header. This may be a problem in some uncommon situations. For exam‐ ple, a .lzma decompressor in an embedded device might work only with files that have known uncompressed size. If you hit this problem, you need to use LZMA Utils or LZMA SDK to create .lzma files with known un‐ compressed size. Unsupported .lzma files The .lzma format allows lc values up to 8, and lp values up to 4. LZMA Utils can decompress files with any lc and lp, but always creates files with lc=3 and lp=0. Creating files with other lc and lp is possible with xz and with LZMA SDK. The implementation of the LZMA1 filter in liblzma requires that the sum of lc and lp must not exceed 4. Thus, .lzma files, which exceed this limitation, cannot be decompressed with xz. LZMA Utils creates only .lzma files which have a dictionary size of 2^n (a power of 2) but accepts files with any dictionary size. liblzma ac‐ cepts only .lzma files which have a dictionary size of 2^n or 2^n + 2^(n-1). This is to decrease false positives when detecting .lzma files. These limitations shouldn't be a problem in practice, since practically all .lzma files have been compressed with settings that liblzma will accept. Trailing garbage When decompressing, LZMA Utils silently ignore everything after the first .lzma stream. In most situations, this is a bug. This also means that LZMA Utils don't support decompressing concatenated .lzma files. If there is data left after the first .lzma stream, xz considers the file to be corrupt unless --single-stream was used. This may break ob‐ scure scripts which have assumed that trailing garbage is ignored. NOTES Compressed output may vary The exact compressed output produced from the same uncompressed input file may vary between XZ Utils versions even if compression options are identical. This is because the encoder can be improved (faster or bet‐ ter compression) without affecting the file format. The output can vary even between different builds of the same XZ Utils version, if different build options are used. The above means that once --rsyncable has been implemented, the result‐ ing files won't necessarily be rsyncable unless both old and new files have been compressed with the same xz version. This problem can be fixed if a part of the encoder implementation is frozen to keep rsynca‐ ble output stable across xz versions. Embedded .xz decompressors Embedded .xz decompressor implementations like XZ Embedded don't neces‐ sarily support files created with integrity check types other than none and crc32. Since the default is --check=crc64, you must use --check=none or --check=crc32 when creating files for embedded systems. Outside embedded systems, all .xz format decompressors support all the check types, or at least are able to decompress the file without veri‐ fying the integrity check if the particular check is not supported. XZ Embedded supports BCJ filters, but only with the default start off‐ set. EXAMPLES Basics Compress the file foo into foo.xz using the default compression level (-6), and remove foo if compression is successful: xz foo Decompress bar.xz into bar and don't remove bar.xz even if decompres‐ sion is successful: xz -dk bar.xz Create baz.tar.xz with the preset -4e (-4 --extreme), which is slower than the default -6, but needs less memory for compression and decom‐ pression (48 MiB and 5 MiB, respectively): tar cf - baz | xz -4e > baz.tar.xz A mix of compressed and uncompressed files can be decompressed to stan‐ dard output with a single command: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Parallel compression of many files On GNU and *BSD, find(1) and xargs(1) can be used to parallelize com‐ pression of many files: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 The -P option to xargs(1) sets the number of parallel xz processes. The best value for the -n option depends on how many files there are to be compressed. If there are only a couple of files, the value should probably be 1; with tens of thousands of files, 100 or even more may be appropriate to reduce the number of xz processes that xargs(1) will eventually create. The option -T1 for xz is there to force it to single-threaded mode, be‐ cause xargs(1) is used to control the amount of parallelization. Robot mode Calculate how many bytes have been saved in total after compressing multiple files: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' A script may want to know that it is using new enough xz. The follow‐ ing sh(1) script checks that the version number of the xz tool is at least 5.0.0. This method is compatible with old beta versions, which didn't support the --robot option: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Set a memory usage limit for decompression using XZ_OPT, but if a limit has already been set, don't increase it: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Custom compressor filter chains The simplest use for custom filter chains is customizing a LZMA2 pre‐ set. This can be useful, because the presets cover only a subset of the potentially useful combinations of compression settings. The CompCPU columns of the tables from the descriptions of the options -0 ... -9 and --extreme are useful when customizing LZMA2 presets. Here are the relevant parts collected from those two tables: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 If you know that a file requires somewhat big dictionary (for example, 32 MiB) to compress well, but you want to compress it quicker than xz -8 would do, a preset with a low CompCPU value (for example, 1) can be modified to use a bigger dictionary: xz --lzma2=preset=1,dict=32MiB foo.tar With certain files, the above command may be faster than xz -6 while compressing significantly better. However, it must be emphasized that only some files benefit from a big dictionary while keeping the CompCPU value low. The most obvious situation, where a big dictionary can help a lot, is an archive containing very similar files of at least a few megabytes each. The dictionary size has to be significantly bigger than any individual file to allow LZMA2 to take full advantage of the similarities between consecutive files. If very high compressor and decompressor memory usage is fine, and the file being compressed is at least several hundred megabytes, it may be useful to use an even bigger dictionary than the 64 MiB that xz -9 would use: xz -vv --lzma2=dict=192MiB big_foo.tar Using -vv (--verbose --verbose) like in the above example can be useful to see the memory requirements of the compressor and decompressor. Re‐ member that using a dictionary bigger than the size of the uncompressed file is waste of memory, so the above command isn't useful for small files. Sometimes the compression time doesn't matter, but the decompressor memory usage has to be kept low, for example, to make it possible to decompress the file on an embedded system. The following command uses -6e (-6 --extreme) as a base and sets the dictionary to only 64 KiB. The resulting file can be decompressed with XZ Embedded (that's why there is --check=crc32) using about 100 KiB of memory. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo If you want to squeeze out as many bytes as possible, adjusting the number of literal context bits (lc) and number of position bits (pb) can sometimes help. Adjusting the number of literal position bits (lp) might help too, but usually lc and pb are more important. For example, a source code archive contains mostly US-ASCII text, so something like the following might give slightly (like 0.1 %) smaller file than xz -6e (try also without lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Using another filter together with LZMA2 can improve compression with certain file types. For example, to compress a x86-32 or x86-64 shared library using the x86 BCJ filter: xz --x86 --lzma2 libfoo.so Note that the order of the filter options is significant. If --x86 is specified after --lzma2, xz will give an error, because there cannot be any filter after LZMA2, and also because the x86 BCJ filter cannot be used as the last filter in the chain. The Delta filter together with LZMA2 can give good results with bitmap images. It should usually beat PNG, which has a few more advanced fil‐ ters than simple delta but uses Deflate for the actual compression. The image has to be saved in uncompressed format, for example, as un‐ compressed TIFF. The distance parameter of the Delta filter is set to match the number of bytes per pixel in the image. For example, 24-bit RGB bitmap needs dist=3, and it is also good to pass pb=0 to LZMA2 to accommodate the three-byte alignment: xz --delta=dist=3 --lzma2=pb=0 foo.tiff If multiple images have been put into a single archive (for example, .tar), the Delta filter will work on that too as long as all images have the same number of bytes per pixel. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html> Tukaani 2024-12-30 XZ(1)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - сравнивают сжатые файлы SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp и xzdiff сравнивают несжатое содержимое двух файлов. Несжатые данные и опции передаются в cmp(1) или diff(1), если не указаны опции --help или --version. Если указаны оба file1 и file2, они могут быть несжатыми файлами или файлами в форматах, которые могут распаковывать xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1). Необходимые команды для распаковки определяются по суффиксам имён файлов file1 и file2. Файл с неизвестным суффиксом считается либо несжатым, либо в формате, который может распаковывать xz(1). Если предоставлено только одно имя файла, file1 должен иметь суффикс поддерживаемого формата сжатия, и имя для file2 предполагается как file1 без суффикса формата сжатия. Команды lzcmp и lzdiff предоставлены для обратной совместимости с LZMA Utils. EXIT STATUS Если происходит ошибка распаковки, код завершения равен 2. В противном случае используется код завершения cmp(1) или diff(1). SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - compare compressed files SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp and xzdiff compare uncompressed contents of two files. Uncom‐ pressed data and options are passed to cmp(1) or diff(1) unless --help or --version is specified. If both file1 and file2 are specified, they can be uncompressed files or files in formats that xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) can decompress. The required decompression commands are deter‐ mined from the filename suffixes of file1 and file2. A file with an unknown suffix is assumed to be either uncompressed or in a format that xz(1) can decompress. If only one filename is provided, file1 must have a suffix of a sup‐ ported compression format and the name for file2 is assumed to be file1 with the compression format suffix removed. The commands lzcmp and lzdiff are provided for backward compatibility with LZMA Utils. EXIT STATUS If a decompression error occurs, the exit status is 2. Otherwise the exit status of cmp(1) or diff(1) is used. SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZDEC(1) XZ Utils XZDEC(1) NAME xzdec, lzmadec - Малые декомпрессоры для файлов .xz и .lzma SYNOPSIS xzdec [option...] [file...] lzmadec [option...] [file...] DESCRIPTION xzdec — это инструмент на основе liblzma, предназначенный только для декомпрессии файлов .xz (и только .xz). xzdec предназначен для использования как замена xz(1) в наиболее распространённых ситуациях, где скрипт написан для использования xz --decompress --stdout (и, возможно, нескольких других часто используемых опций) для декомпрессии файлов .xz. lzmadec идентичен xzdec, за исключением того, что lzmadec поддерживает файлы .lzma вместо файлов .xz. Чтобы уменьшить размер исполняемого файла, xzdec не поддерживает многопоточность или локализацию и не читает опции из переменных окружения XZ_DEFAULTS и XZ_OPT. xzdec не поддерживает отображение промежуточной информации о прогрессе: отправка SIGINFO в xzdec ничего не делает, но отправка SIGUSR1 завершает процесс вместо отображения информации о прогрессе. OPTIONS -d, --decompress, --uncompress Игнорируется для совместимости с xz(1). xzdec поддерживает только декомпрессию. -k, --keep Игнорируется для совместимости с xz(1). xzdec никогда не создаёт или не удаляет никаких файлов. -c, --stdout, --to-stdout Игнорируется для совместимости с xz(1). xzdec всегда записывает декомпрессированные данные в стандартный вывод. -q, --quiet Указание этой опции один раз ничего не делает, поскольку xzdec никогда не отображает предупреждения или уведомления. Укажите эту опцию дважды, чтобы подавить ошибки. -Q, --no-warn Игнорируется для совместимости с xz(1). xzdec никогда не использует код выхода 2. -h, --help Отобразить сообщение помощи и успешно выйти. -V, --version Отобразить номер версии xzdec и liblzma. EXIT STATUS 0 Всё прошло успешно. 1 Произошла ошибка. xzdec не имеет сообщений предупреждений, как у xz(1), поэтому код выхода 2 не используется xzdec. NOTES Используйте xz(1) вместо xzdec или lzmadec для повседневного использования. xzdec или lzmadec предназначены только для ситуаций, где важно иметь декомпрессор меньшего размера, чем полнофункциональный xz(1). xzdec и lzmadec не такие уж маленькие. Размер можно уменьшить ещё больше, отключив функции в liblzma на этапе компиляции, но это обычно не рекомендуется для исполняемых файлов, распространяемых в типичных дистрибутивах не-встроенных операционных систем. Если вам нужен действительно маленький декомпрессор для .xz, рассмотрите использование XZ Embedded. SEE ALSO xz(1) XZ Embedded: <https://tukaani.org/xz/embedded.html> Tukaani 2024-04-08 XZDEC(1)
XZDEC(1) XZ Utils XZDEC(1) NAME xzdec, lzmadec - Small .xz and .lzma decompressors SYNOPSIS xzdec [option...] [file...] lzmadec [option...] [file...] DESCRIPTION xzdec is a liblzma-based decompression-only tool for .xz (and only .xz) files. xzdec is intended to work as a drop-in replacement for xz(1) in the most common situations where a script has been written to use xz --decompress --stdout (and possibly a few other commonly used options) to decompress .xz files. lzmadec is identical to xzdec except that lz‐ madec supports .lzma files instead of .xz files. To reduce the size of the executable, xzdec doesn't support multi‐ threading or localization, and doesn't read options from XZ_DEFAULTS and XZ_OPT environment variables. xzdec doesn't support displaying in‐ termediate progress information: sending SIGINFO to xzdec does nothing, but sending SIGUSR1 terminates the process instead of displaying progress information. OPTIONS -d, --decompress, --uncompress Ignored for xz(1) compatibility. xzdec supports only decompres‐ sion. -k, --keep Ignored for xz(1) compatibility. xzdec never creates or removes any files. -c, --stdout, --to-stdout Ignored for xz(1) compatibility. xzdec always writes the decom‐ pressed data to standard output. -q, --quiet Specifying this once does nothing since xzdec never displays any warnings or notices. Specify this twice to suppress errors. -Q, --no-warn Ignored for xz(1) compatibility. xzdec never uses the exit sta‐ tus 2. -h, --help Display a help message and exit successfully. -V, --version Display the version number of xzdec and liblzma. EXIT STATUS 0 All was good. 1 An error occurred. xzdec doesn't have any warning messages like xz(1) has, thus the exit status 2 is not used by xzdec. NOTES Use xz(1) instead of xzdec or lzmadec for normal everyday use. xzdec or lzmadec are meant only for situations where it is important to have a smaller decompressor than the full-featured xz(1). xzdec and lzmadec are not really that small. The size can be reduced further by dropping features from liblzma at compile time, but that shouldn't usually be done for executables distributed in typical non- embedded operating system distributions. If you need a truly small .xz decompressor, consider using XZ Embedded. SEE ALSO xz(1) XZ Embedded: <https://tukaani.org/xz/embedded.html> Tukaani 2024-04-08 XZDEC(1)
XZDEC(1) XZ Utils XZDEC(1) NAME xzdec, lzmadec - Маленькие декомпрессоры для .xz и .lzma файлов SYNOPSIS xzdec [option...] [file...] lzmadec [option...] [file...] DESCRIPTION xzdec — это инструмент на основе liblzma, предназначенный только для декомпрессии файлов .xz (и только .xz). xzdec предназначен для использования в качестве замены xz(1) в наиболее распространенных ситуациях, где скрипт написан для использования xz --decompress --stdout (и, возможно, нескольких других часто используемых опций) для декомпрессии файлов .xz. lzmadec идентичен xzdec, за исключением того, что lzmadec поддерживает файлы .lzma вместо файлов .xz. Для уменьшения размера исполняемого файла xzdec не поддерживает многопоточность или локализацию и не читает опции из переменных окружения XZ_DEFAULTS и XZ_OPT. xzdec не поддерживает отображение промежуточной информации о прогрессе: отправка SIGINFO xzdec ничего не делает, но отправка SIGUSR1 завершает процесс вместо отображения информации о прогрессе. OPTIONS -d, --decompress, --uncompress Игнорируется для совместимости с xz(1). xzdec поддерживает только декомпрессию. -k, --keep Игнорируется для совместимости с xz(1). xzdec никогда не создает и не удаляет никаких файлов. -c, --stdout, --to-stdout Игнорируется для совместимости с xz(1). xzdec всегда записывает декомпрессированные данные в стандартный вывод. -q, --quiet Указание этой опции один раз ничего не делает, поскольку xzdec никогда не отображает предупреждения или уведомления. Укажите эту опцию дважды, чтобы подавить ошибки. -Q, --no-warn Игнорируется для совместимости с xz(1). xzdec никогда не использует код выхода 2. -h, --help Отобразить сообщение помощи и успешно выйти. -V, --version Отобразить номер версии xzdec и liblzma. EXIT STATUS 0 Всё в порядке. 1 Произошла ошибка. xzdec не имеет сообщений предупреждений, как у xz(1), поэтому код выхода 2 не используется xzdec. NOTES Используйте xz(1) вместо xzdec или lzmadec для повседневного использования. xzdec или lzmadec предназначены только для ситуаций, где важно иметь декомпрессор меньшего размера, чем полноценный xz(1). xzdec и lzmadec не такие уж маленькие. Размер можно уменьшить дальше, отключив функции в liblzma на этапе компиляции, но это обычно не рекомендуется для исполняемых файлов, распространяемых в типичных не-встроенных операционных системах. Если вам нужен действительно маленький декомпрессор для .xz, рассмотрите использование XZ Embedded. SEE ALSO xz(1) XZ Embedded: <https://tukaani.org/xz/embedded.html> Tukaani 2024-04-08 XZDEC(1)
XZDEC(1) XZ Utils XZDEC(1) NAME xzdec, lzmadec - Small .xz and .lzma decompressors SYNOPSIS xzdec [option...] [file...] lzmadec [option...] [file...] DESCRIPTION xzdec is a liblzma-based decompression-only tool for .xz (and only .xz) files. xzdec is intended to work as a drop-in replacement for xz(1) in the most common situations where a script has been written to use xz --decompress --stdout (and possibly a few other commonly used options) to decompress .xz files. lzmadec is identical to xzdec except that lz‐ madec supports .lzma files instead of .xz files. To reduce the size of the executable, xzdec doesn't support multi‐ threading or localization, and doesn't read options from XZ_DEFAULTS and XZ_OPT environment variables. xzdec doesn't support displaying in‐ termediate progress information: sending SIGINFO to xzdec does nothing, but sending SIGUSR1 terminates the process instead of displaying progress information. OPTIONS -d, --decompress, --uncompress Ignored for xz(1) compatibility. xzdec supports only decompres‐ sion. -k, --keep Ignored for xz(1) compatibility. xzdec never creates or removes any files. -c, --stdout, --to-stdout Ignored for xz(1) compatibility. xzdec always writes the decom‐ pressed data to standard output. -q, --quiet Specifying this once does nothing since xzdec never displays any warnings or notices. Specify this twice to suppress errors. -Q, --no-warn Ignored for xz(1) compatibility. xzdec never uses the exit sta‐ tus 2. -h, --help Display a help message and exit successfully. -V, --version Display the version number of xzdec and liblzma. EXIT STATUS 0 All was good. 1 An error occurred. xzdec doesn't have any warning messages like xz(1) has, thus the exit status 2 is not used by xzdec. NOTES Use xz(1) instead of xzdec or lzmadec for normal everyday use. xzdec or lzmadec are meant only for situations where it is important to have a smaller decompressor than the full-featured xz(1). xzdec and lzmadec are not really that small. The size can be reduced further by dropping features from liblzma at compile time, but that shouldn't usually be done for executables distributed in typical non- embedded operating system distributions. If you need a truly small .xz decompressor, consider using XZ Embedded. SEE ALSO xz(1) XZ Embedded: <https://tukaani.org/xz/embedded.html> Tukaani 2024-04-08 XZDEC(1)
XZ(1) XZ Utils XZ(1) НАЗВАНИЕ xz, unxz, xzcat, lzma, unlzma, lzcat - Сжатие или распаковка файлов .xz и .lzma СИНОПСИС xz [option...] [file...] ПСЕВДОНИМЫ КОМАНД unxz эквивалентен xz --decompress. xzcat эквивалентен xz --decompress --stdout. lzma эквивалентен xz --format=lzma. unlzma эквивалентен xz --format=lzma --decompress. lzcat эквивалентен xz --format=lzma --decompress --stdout. При написании сценариев, которые требуют распаковки файлов, рекомендуется всегда использовать имя xz с подходящими аргументами (xz -d или xz -dc) вместо имён unxz и xzcat. ОПИСАНИЕ xz - это универсальный инструмент сжатия данных с синтаксисом командной строки, похожим на gzip(1) и bzip2(1). Исходный формат файлов - .xz, но также поддерживается устаревший формат .lzma, используемый в LZMA Utils, и необработанные сжатые потоки без заголовков контейнера. Кроме того, поддерживается распаковка формата .lz, используемого lzip. xz сжимает или распаковывает каждый файл в соответствии с выбранным режимом операции. Если файлы не указаны или указан файл -, xz читает из стандартного ввода и записывает обработанные данные в стандартный вывод. xz отказывается (выводит ошибку и пропускает файл) записывать сжатые данные в стандартный вывод, если он является терминалом. Аналогично, xz отказывается читать сжатые данные из стандартного ввода, если он является терминалом. Если не указан --stdout, файлы, отличные от -, записываются в новый файл, чьё имя выводится из имени исходного файла: • При сжатии, суффикс целевого формата файла (.xz или .lzma) добавляется к имени исходного файла для получения имени целевого файла. • При распаковке, суффикс .xz, .lzma или .lz удаляется из имени файла для получения имени целевого файла. xz также распознаёт суффиксы .txz и .tlz и заменяет их на суффикс .tar. Если целевой файл уже существует, выводится ошибка и файл пропускается. Если не осуществляется запись в стандартный вывод, xz выведет предупреждение и пропустит файл, если выполняется одно из следующих условий: • Файл не является обычным файлом. Символические ссылки не следуются, и поэтому они не считаются обычными файлами. • У файла более одной жёсткой ссылки. • У файла установлен бит setuid, setgid или sticky. • Режим операции установлен на сжатие, и у файла уже есть суффикс целевого формата файла (.xz или .txz при сжатии в формат .xz, и .lzma или .tlz при сжатии в формат .lzma). • Режим операции установлен на распаковку, и у файла нет суффикса ни одного из поддерживаемых форматов файлов (.xz, .txz, .lzma, .tlz или .lz). После успешного сжатия или распаковки файла xz копирует владельца, группу, права доступа, время доступа и время модификации из исходного файла в целевой файл. Если копирование группы не удаётся, права доступа изменяются так, чтобы целевой файл не стал доступным для пользователей, у которых не было доступа к исходному файлу. xz пока не поддерживает копирование другой метаданных, такой как списки контроля доступа или расширенные атрибуты. После успешного закрытия целевого файла исходный файл удаляется, если не указан --keep. Исходный файл никогда не удаляется, если вывод осуществляется в стандартный вывод или если возникает ошибка. Отправка сигнала SIGINFO или SIGUSR1 процессу xz заставляет его вывести информацию о прогрессе в стандартный вывод ошибок. Это имеет ограниченное применение, поскольку если стандартный вывод ошибок является терминалом, использование --verbose отобразит автоматически обновляемый индикатор прогресса. Использование памяти Использование памяти xz варьируется от нескольких сотен килобайтов до нескольких гигабайт в зависимости от настроек сжатия. Настройки, используемые при сжатии файла, определяют требования к памяти декомпрессора. Обычно декомпрессору требуется 5 %–20 % от количества памяти, которое потребовалось компрессору для создания файла. Например, распаковка файла, созданного с xz -9, в настоящее время требует 65 MiB памяти. Тем не менее, возможно наличие файлов .xz, которые требуют нескольких гигабайт памяти для распаковки. Пользователи старых систем могут найти возможность очень большого использования памяти раздражающей. Чтобы предотвратить неприятные сюрпризы, xz имеет встроенный лимитер использования памяти, который отключён по умолчанию. Хотя некоторые операционные системы предоставляют способы ограничения использования памяти процессами, полагаться на это не было сочтено достаточно гибким (например, использование ulimit(1) для ограничения виртуальной памяти может нарушить mmap(2)). Лимитер использования памяти можно включить с помощью опции командной строки --memlimit=limit. Часто удобнее включить лимитер по умолчанию, установив переменную окружения XZ_DEFAULTS, например, XZ_DEFAULTS=--memlimit=150MiB. Возможна установка лимитов отдельно для сжатия и распаковки с помощью --memlimit-compress=limit и --memlimit-decompress=limit. Использование этих двух опций вне XZ_DEFAULTS редко бывает полезным, поскольку один запуск xz не может выполнять одновременно сжатие и распаковку, и --memlimit=limit (или -M limit) короче для ввода в командной строке. Если указанный лимит использования памяти превышен при распаковке, xz выведет ошибку и распаковка файла завершится неудачей. Если лимит превышен при сжатии, xz попытается уменьшить настройки, чтобы лимит больше не превышался (кроме случаев использования --format=raw или --no-adjust). Таким образом, операция не завершится неудачей, если лимит не слишком мал. Уменьшение настроек происходит поэтапно, не совпадая с предустановками уровней сжатия, например, если лимит немного меньше, чем требуется для xz -9, настройки уменьшатся только немного, а не до xz -8. Конкатенация и заполнение файлов .xz Возможна конкатенация файлов .xz как есть. xz будет распаковывать такие файлы, как будто это один файл .xz. Возможна вставка заполнения между конкатенируемыми частями или после последней части. Заполнение должно состоять из нулевых байтов, и его размер должен быть кратным четырём байтам. Это может быть полезно, например, если файл .xz хранится на носителе, который измеряет размеры файлов в блоках по 512 байтов. Конкатенация и заполнение не допускаются для файлов .lzma или необработанных потоков. ОПЦИИ Суффиксы целых чисел и специальные значения В большинстве мест, где ожидается целочисленный аргумент, поддерживается необязательный суффикс для удобного указания больших целых чисел. Между целым числом и суффиксом не должно быть пробелов. KiB Умножает целое число на 1 024 (2^10). Ki, k, kB, K и KB принимаются как синонимы KiB. MiB Умножает целое число на 1 048 576 (2^20). Mi, m, M и MB принимаются как синонимы MiB. GiB Умножает целое число на 1 073 741 824 (2^30). Gi, g, G и GB принимаются как синонимы GiB. Специальное значение max может использоваться для указания максимального поддерживаемого целочисленного значения опцией. Режимы операции Если указано несколько опций режима операции, последняя вступает в силу. -z, --compress Сжатие. Это режим операции по умолчанию, если ни одна опция режима операции не указана и другой режим не подразумевается из имени команды (например, unxz подразумевает --decompress). После успешного сжатия исходный файл удаляется, если вывод осуществляется не в стандартный вывод и не указан --keep. -d, --decompress, --uncompress Распаковка. После успешной распаковки исходный файл удаляется, если вывод осуществляется не в стандартный вывод и не указан --keep. -t, --test Проверка целостности сжатых файлов. Эта опция эквивалентна --decompress --stdout, за исключением того, что распакованные данные отбрасываются вместо записи в стандартный вывод. Файлы не создаются и не удаляются. -l, --list Вывод информации о сжатых файлах. Не производится распакованный вывод, и файлы не создаются или не удаляются. В режиме списка программа не может читать сжатые данные из стандартного ввода или из других неподвижных источников. По умолчанию список показывает базовую информацию о файлах, один файл на строку. Для получения более детальной информации используйте также опцию --verbose. Для ещё большей информации используйте --verbose дважды, но учтите, что это может быть медленно, поскольку получение всей дополнительной информации требует многих поисков. Ширина подробного вывода превышает 80 символов, поэтому перенаправление вывода в, например, less -S может быть удобным, если терминал не достаточно широкий. Точный вывод может варьироваться между версиями xz и разными локалями. Для машинно-читаемого вывода используйте --robot --list. Модификаторы операций -k, --keep Не удалять исходные файлы. С версии xz 5.2.6 эта опция также заставляет xz сжимать или распаковывать, даже если вход является символической ссылкой на обычный файл, имеет более одной жёсткой ссылки или установлен бит setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. В более ранних версиях это делалось только с --force. -f, --force Эта опция имеет несколько эффектов: • Если целевой файл уже существует, удалить его перед сжатием или распаковкой. • Сжимать или распаковывать, даже если вход является символической ссылкой на обычный файл, имеет более одной жёсткой ссылки или установлен бит setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. • При использовании с --decompress --stdout, если xz не может распознать тип исходного файла, скопировать исходный файл как есть в стандартный вывод. Это позволяет использовать xzcat --force как cat(1) для файлов, которые не были сжаты с xz. Обратите внимание, что в будущем xz может поддерживать новые форматы сжатых файлов, что может заставить xz распаковывать больше типов файлов вместо копирования их как есть в стандартный вывод. --format=format можно использовать, чтобы ограничить xz распаковкой только одного формата файла. -c, --stdout, --to-stdout Записывать сжатые или распакованные данные в стандартный вывод вместо файла. Это подразумевает --keep. --single-stream Распаковывать только первый поток .xz и молча игнорировать возможные оставшиеся данные входа после потока. Нормально такие завершающие мусорные данные заставляют xz вывести ошибку. xz никогда не распаковывает более одного потока из файлов .lzma или необработанных потоков, но эта опция всё равно заставляет xz игнорировать возможные завершающие данные после файла .lzma или необработанного потока. Эта опция не имеет эффекта, если режим операции не --decompress или --test. --no-sparse Отключить создание разреженных файлов. По умолчанию, если распаковывается в обычный файл, xz пытается сделать файл разреженным, если распакованные данные содержат длинные последовательности двоичных нулей. Это также работает при записи в стандартный вывод, если стандартный вывод подключён к обычному файлу и выполняются определённые дополнительные условия для безопасности. Создание разреженных файлов может сэкономить место на диске и ускорить распаковку, уменьшив объём операций ввода/вывода. -S .suf, --suffix=.suf При сжатии, использовать .suf в качестве суффикса для целевого файла вместо .xz или .lzma. Если вывод не осуществляется в стандартный вывод и у исходного файла уже есть суффикс .suf, выводится предупреждение и файл пропускается. При распаковке, распознавать файлы с суффиксом .suf в дополнение к файлам с суффиксами .xz, .txz, .lzma, .tlz или .lz. Если у исходного файла суффикс .suf, он удаляется для получения имени целевого файла. При сжатии или распаковке необработанных потоков (--format=raw), суффикс всегда должен быть указан, если вывод не осуществляется в стандартный вывод, поскольку для необработанных потоков нет суффикса по умолчанию. --files[=file] Читать имена файлов для обработки из file; если file не указан, имена файлов читаются из стандартного ввода. Имена файлов должны завершаться символом новой строки. Дефис (-) воспринимается как обычное имя файла; он не означает стандартный ввод. Если имена файлов также указаны как аргументы командной строки, они обрабатываются перед именами, прочитанными из file. --files0[=file] Это идентично --files[=file], за исключением того, что каждое имя файла должно завершаться нулевым символом. Базовые опции формата файла и сжатия -F format, --format=format Указать формат файла для сжатия или распаковки: auto Это значение по умолчанию. При сжатии auto эквивалентно xz. При распаковке формат входного файла определяется автоматически. Обратите внимание, что необработанные потоки (созданные с --format=raw) не могут быть автоматически определены. xz Сжимать в формат .xz или принимать только файлы .xz при распаковке. lzma, alone Сжимать в устаревший формат .lzma или принимать только файлы .lzma при распаковке. Альтернативное имя alone предоставлено для обратной совместимости с LZMA Utils. lzip При распаковке принимать только файлы .lz. Сжатие не поддерживается. Поддерживаются версия формата 0 и нерасширенная версия 1. Файлы версии 0 создавались lzip 1.3 и старше. Такие файлы редко встречаются, но могут быть найдены в архивах файлов, поскольку несколько исходных пакетов были выпущены в этом формате. У пользователей могут быть старые личные файлы в этом формате. Поддержка распаковки версии формата 0 была удалена в lzip 1.18. lzip 1.4 и старше создают файлы в формате версии 1. Расширение маркера синхронизированного сброса для версии формата 1 было добавлено в lzip 1.6. Это расширение редко используется и не поддерживается xz (диагностируется как повреждённый вход). raw Сжимать или распаковывать необработанный поток (без заголовков). Это предназначено только для продвинутых пользователей. Для декодирования необработанных потоков вам нужно использовать --format=raw и явно указать цепочку фильтров, которая обычно хранилась бы в заголовках контейнера. -C check, --check=check Указать тип проверки целостности. Проверка рассчитывается из несжатых данных и хранится в файле .xz. Эта опция имеет эффект только при сжатии в формат .xz; формат .lzma не поддерживает проверки целостности. Проверка целостности (если есть) проверяется при распаковке файла .xz. Поддерживаемые типы проверок: none Не рассчитывать проверку целостности. Это обычно плохая идея. Это может быть полезно, когда целостность данных проверяется другими средствами в любом случае. crc32 Рассчитать CRC32 с использованием полинома из IEEE-802.3 (Ethernet). crc64 Рассчитать CRC64 с использованием полинома из ECMA-182. Это значение по умолчанию, поскольку оно немного лучше, чем CRC32, для обнаружения повреждённых файлов, а разница в скорости незначительна. sha256 Рассчитать SHA-256. Это немного медленнее, чем CRC32 и CRC64. Целостность заголовков .xz всегда проверяется с CRC32. Изменить или отключить это невозможно. --ignore-check Не проверять проверку целостности сжатых данных при распаковке. Значения CRC32 в заголовках .xz всё равно будут проверены нормально. Не используйте эту опцию, если вы не знаете, что делаете. Возможные причины использования этой опции: • Попытка восстановить данные из повреждённого файла .xz. • Увеличение скорости распаковки. Это имеет значение в основном с SHA-256 или с файлами, которые сжаты очень хорошо. Рекомендуется не использовать эту опцию для этой цели, если целостность файла проверяется внешне другим способом. -0 ... -9 Выбрать предустановленный уровень сжатия. По умолчанию -6. Если указано несколько предустановленных уровней, последний вступает в силу. Если уже указана пользовательская цепочка фильтров, установка предустановленного уровня сжатия сбрасывает пользовательскую цепочку фильтров. Различия между предустановками более значительны, чем в gzip(1) и bzip2(1). Выбранные настройки сжатия определяют требования к памяти декомпрессора, поэтому использование слишком высокого уровня предустановки может сделать распаковку болезненной на старой системе с малым количеством ОЗУ. В частности, не стоит слепо использовать -9 для всего, как это часто бывает с gzip(1) и bzip2(1). -0 ... -3 Это относительно быстрые предустановки. -0 иногда быстрее, чем gzip -9, при гораздо лучшем сжатии. Более высокие значения часто имеют скорость, сравнимую с bzip2(1), с соотношением сжатия, сравнимым или лучше, хотя результаты сильно зависят от типа сжимаемых данных. -4 ... -6 Хорошее до очень хорошего сжатия при разумном использовании памяти декомпрессора даже для старых систем. -6 - значение по умолчанию, которое обычно является хорошим выбором для распространения файлов, которые должны быть распакованы даже на системах с всего 16 MiB ОЗУ. (-5e или -6e также стоит рассмотреть. См. --extreme.) -7 ... -9 Это как -6, но с более высокими требованиями к памяти компрессора и декомпрессора. Это полезно только при сжатии файлов больше 8 MiB, 16 MiB и 32 MiB соответственно. На том же оборудовании скорость распаковки примерно постоянна в количестве байтов сжатых данных в секунду. Другими словами, чем лучше сжатие, тем быстрее обычно будет распаковка. Это также означает, что количество несжатого вывода, производимого в секунду, может сильно варьироваться. В следующей таблице суммируются особенности предустановок: Preset;DictSize;CompCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Описания столбцов: • DictSize - размер словаря LZMA2. Трата памяти на словарь больше, чем размер несжатого файла, бесполезна. Поэтому стоит избегать использования предустановок -7 ... -9, если в них нет реальной необходимости. При -6 и ниже, количество потраченной впустую памяти обычно достаточно низкое, чтобы не иметь значения. • CompCPU - упрощённое представление настроек LZMA2, влияющих на скорость сжатия. Размер словаря тоже влияет на скорость, так что, хотя CompCPU одинаков для уровней -6 ... -9, более высокие уровни всё равно склонны быть немного медленнее. Для получения ещё более медленного и, возможно, лучшего сжатия см. --extreme. • CompMem - требования к памяти компрессора в однонитевом режиме. Это может немного варьироваться между версиями xz. • DecMem - требования к памяти декомпрессора. То есть, настройки сжатия определяют требования к памяти декомпрессора. Точное использование памяти декомпрессором немного больше, чем размер словаря LZMA2, но значения в таблице округлены вверх до следующего полного MiB. Требования к памяти в многопоточном режиме значительно выше, чем в однонитевом. С значением --block-size по умолчанию, каждый поток требует 3*3*DictSize плюс CompMem или DecMem. Например, четыре потока с предустановкой -6 требуют 660–670 MiB памяти. -e, --extreme Использовать более медленную вариацию выбранного уровня предустановки сжатия (-0 ... -9), чтобы, возможно, получить немного лучшее соотношение сжатия, но с неудачей это может сделать его хуже. Использование памяти декомпрессором не затрагивается, но использование памяти компрессором увеличивается немного на уровнях предустановок -0 ... -3. Поскольку есть две предустановки с размерами словарей 4 MiB и 8 MiB, предустановки -3e и -5e используют немного более быстрые настройки (нижний CompCPU), чем -4e и -6e соответственно. Таким образом, никакие две предустановки не идентичны. Preset;DictSize;CompCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB Например, всего четыре предустановки используют словарь 8 MiB, и их порядок от самой быстрой к самой медленной - -5, -6, -5e и -6e. --fast --best Эти - несколько вводящие в заблуждение псевдонимы для -0 и -9 соответственно. Они предоставлены только для обратной совместимости с LZMA Utils. Избегайте использования этих опций. --block-size=size При сжатии в формат .xz, разделить входные данные на блоки размером size байтов. Блоки сжимаются независимо друг от друга, что помогает с многопоточностью и делает возможной ограниченную случайную распаковку. Эта опция обычно используется для переопределения размера блока по умолчанию в многопоточном режиме, но её можно использовать и в однонитевом режиме. В многопоточном режиме примерно 3*size байтов будет выделено в каждом потоке для буферизации ввода и вывода. Значение по умолчанию - три размера словаря LZMA2 или 1 MiB, в зависимости от того, что больше. Обычно хорошее значение - 2–4 раза размер словаря LZMA2 или по крайней мере 1 MiB. Использование size меньше, чем размер словаря LZMA2, - трата ОЗУ, поскольку буфер словаря LZMA2 никогда не будет полностью использован. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Эта информация о размере необходима для многопоточной распаковки. В однонитевом режиме по умолчанию разбиение на блоки не производится. Установка этой опции не влияет на использование памяти. Информация о размере не хранится в заголовках блоков, поэтому файлы, созданные в однонитевом режиме, не будут идентичны файлам, созданным в многопоточном режиме. Отсутствие информации о размере также означает, что xz не сможет распаковывать файлы в многопоточном режиме. --block-list=items При сжатии в формат .xz, начинать новый блок с необязательной пользовательской цепочкой фильтров после указанных интервалов несжатых данных. items - список, разделённый запятыми. Каждый элемент состоит из необязательного номера цепочки фильтров от 0 до 9, за которым следует двоеточие (:) и требуемый размер несжатых данных. Пропуск элемента (две или более последовательных запятых) - сокращение для использования размера и фильтров предыдущего элемента. Если входной файл больше суммы размеров в items, последний элемент повторяется до конца файла. Специальное значение 0 может использоваться как последний размер, чтобы указать, что остаток файла должен быть закодирован как один блок. Альтернативную цепочку фильтров для каждого блока можно указать в сочетании с опциями --filters1=filters ... --filters9=filters. Эти опции определяют цепочки фильтров с идентификатором от 1 до 9. Цепочка фильтров 0 может использоваться для ссылки на цепочку фильтров по умолчанию, которая является той же, что и без указания цепочки фильтров. Идентификатор цепочки фильтров можно использовать перед несжатым размером, за которым следует двоеточие (:). Например, если указать --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB, то блоки будут созданы с использованием: • Цепочки фильтров, указанной в --filters1 и 2 MiB входа • Цепочки фильтров, указанной в --filters3 и 2 MiB входа • Цепочки фильтров, указанной в --filters2 и 4 MiB входа • Цепочки фильтров, указанной в --filters2 и 4 MiB входа • Цепочки фильтров по умолчанию и 2 MiB входа • Цепочки фильтров по умолчанию и 4 MiB входа для каждого блока до конца входа. Если указать размер, превышающий размер блока энкодера (значение по умолчанию в многопоточном режиме или значение, указанное с --block-size=size), энкодер создаст дополнительные блоки, сохраняя границы, указанные в items. Например, если указать --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB и входной файл имеет размер 80 MiB, получим 11 блоков: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10 и 1 MiB. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Это не делается в однонитевом режиме, так что закодированный вывод не будет идентичным тому, что в многопоточном режиме. --flush-timeout=timeout При сжатии, если прошло более timeout миллисекунд (положительное целое число) с предыдущего сброса и чтение дополнительных входных данных заблокировано, все ожидающие входные данные сбрасываются из энкодера и становятся доступными в выходном потоке. Это может быть полезно, если xz используется для сжатия данных, которые передаются по сети. Малые значения timeout делают данные доступными на принимающей стороне с небольшой задержкой, но большие значения дают лучшее соотношение сжатия. Эта функция отключена по умолчанию. Если эта опция указана несколько раз, последняя вступает в силу. Специальное значение timeout 0 может использоваться для явного отключения этой функции. Эта функция недоступна в не-POSIX-системах. Эта функция всё ещё экспериментальна. В настоящее время xz неподходит для распаковки потока в реальном времени из-за того, как xz буферизует. --memlimit-compress=limit Установить лимит использования памяти для сжатия. Если эта опция указана несколько раз, последняя вступает в силу. Если настройки сжатия превышают лимит, xz попытается уменьшить настройки, чтобы лимит больше не превышался, и выведет уведомление, что автоматическая корректировка была произведена. Корректировки производятся в следующем порядке: уменьшение количества потоков, переключение на однонитевой режим, если даже один поток в многопоточном режиме превышает лимит, и наконец, уменьшение размера словаря LZMA2. При сжатии с --format=raw или если указан --no-adjust, только количество потоков может быть уменьшено, поскольку это можно сделать без влияния на сжатый вывод. Если лимит не может быть достигнут даже с корректировками, описанными выше, выводится ошибка и xz завершится с кодом выхода 1. Лимит может быть указан несколькими способами: • Лимит может быть абсолютным значением в байтах. Использование суффикса целых чисел, например MiB, может быть полезным. Пример: --memlimit-compress=80MiB • Лимит может быть указан в процентах от общего физического объёма памяти (ОЗУ). Это может быть полезно, особенно при установке переменной окружения XZ_DEFAULTS в скрипте инициализации оболочки, который общий для разных компьютеров. Таким образом, лимит автоматически будет больше на системах с большим количеством памяти. Пример: --memlimit-compress=70% • Лимит может быть сброшен на значение по умолчанию путём установки на 0. В настоящее время это эквивалентно установке лимита на max (нет лимита использования памяти). Для 32-битного xz есть специальный случай: если лимит был бы более 4020 MiB, лимит устанавливается на 4020 MiB. На MIPS32 используется 2000 MiB. (Значения 0 и max не затрагиваются. Аналогичная функция не существует для распаковки.) Это может быть полезно, когда 32-битный исполняемый файл имеет доступ к 4 GiB адресного пространства (2 GiB на MIPS32), в то время как, надеюсь, не причиняя вреда в других ситуациях. См. также раздел Использование памяти. --memlimit-decompress=limit Установить лимит использования памяти для распаковки. Это также влияет на режим --list. Если операция невозможна без превышения лимита, xz выведет ошибку и распаковка файла завершится неудачей. См. --memlimit-compress=limit для возможных способов указания лимита. --memlimit-mt-decompress=limit Установить лимит использования памяти для многопоточной распаковки. Это может повлиять только на количество потоков; это никогда не заставит xz отказываться от распаковки файла. Если лимит слишком низкий, чтобы позволить какую-либо многопоточность, лимит игнорируется и xz продолжит в однонитевом режиме. Обратите внимание, что если также используется --memlimit-decompress, он будет применяться как к однонитевому, так и к многопоточному режимам, поэтому эффективный лимит для многопоточности никогда не будет выше, чем лимит, установленный с --memlimit-decompress. В отличие от других опций лимита использования памяти, --memlimit-mt-decompress=limit имеет системно-специфическое значение лимита по умолчанию. xz --info-memory можно использовать, чтобы увидеть текущее значение. Эта опция и её значение по умолчанию существуют, потому что без какого-либо лимита многопоточный декомпрессор может в конечном итоге выделить безумное количество памяти для некоторых входных файлов. Если значение лимита по умолчанию слишком низкое на вашей системе, вы можете увеличить лимит, но никогда не устанавливайте его на значение больше, чем объём usable ОЗУ, поскольку с подходящими входными файлами xz попытается использовать это количество памяти, даже с небольшим количеством потоков. Исчерпание памяти или свапинг не улучшат производительность распаковки. См. --memlimit-compress=limit для возможных способов указания лимита. Установка limit на 0 сбрасывает лимит на системно-специфическое значение по умолчанию. -M limit, --memlimit=limit, --memory=limit Это эквивалентно указанию --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Выводить ошибку и выходить, если лимит использования памяти не может быть достигнут без корректировки настроек, влияющих на сжатый вывод. То есть, это предотвращает переключение энкодера из многопоточного режима на однонитевой режим и уменьшение размера словаря LZMA2. Даже при использовании этой опции количество потоков может быть уменьшено, чтобы соответствовать лимиту использования памяти, поскольку это не повлияет на сжатый вывод. Автоматическая корректировка всегда отключена при создании необработанных потоков (--format=raw). -T threads, --threads=threads Указать количество рабочих потоков. Установка threads на специальное значение 0 заставляет xz использовать до такого количества потоков, сколько процессор(ы) системы поддерживают. Фактическое количество потоков может быть меньше threads, если входной файл недостаточно велик для потоков с заданными настройками или если использование большего количества потоков превысит лимит использования памяти. Однонитевой и многопоточный компрессоры производят разный вывод. Однонитевой компрессор даст наименьший размер файла, но только вывод от многопоточного компрессора можно распаковывать с использованием нескольких потоков. Установка threads на 1 использует однонитевой режим. Установка threads на любое другое значение, включая 0, будет использовать многопоточный компрессор, даже если система поддерживает только один аппаратный поток. (xz 5.2.x использовал однонитевой режим в этой ситуации.) Чтобы использовать многопоточный режим с одним потоком, установите threads на +1. Префикс + не имеет эффекта с значениями, отличными от 1. Лимит использования памяти всё равно может заставить xz переключиться на однонитевой режим, если не используется --no-adjust. Поддержка префикса + была добавлена в xz 5.4.0. Если запрошено автоматическое количество потоков и лимит использования памяти не указан, будет использован системно-специфический лимит по умолчанию, чтобы, возможно, ограничить количество потоков. Это мягкий лимит в том смысле, что он игнорируется, если количество потоков становится единицей, таким образом, мягкий лимит никогда не остановит xz от сжатия или распаковки. Этот лимит по умолчанию не заставит xz переключиться из многопоточного режима на однонитевой режим. Активные лимиты можно увидеть с xz --info-memory. В настоящее время единственный метод потоков - разделить вход на блоки и сжать их независимо друг от друга. Размер блока по умолчанию зависит от уровня сжатия и может быть переопределён с опцией --block-size=size. Многопоточная распаковка работает только с файлами, которые содержат несколько блоков с информацией о размере в заголовках блоков. Все достаточно большие файлы, сжатые в многопоточном режиме, соответствуют этому условию, но файлы, сжатые в однонитевом режиме, нет, даже если использовался --block-size=size. Значение threads по умолчанию - 0. В xz 5.4.x и старше значение по умолчанию - 1. Пользовательские цепочки фильтров компрессора Пользовательская цепочка фильтров позволяет указывать настройки сжатия в деталях вместо использования настроек, связанных с предустановками. Когда указана пользовательская цепочка фильтров, опции предустановок (-0 ... -9 и --extreme), указанные ранее в командной строке, забываются. Если опция предустановки указана после одной или более опций пользовательской цепочки фильтров, новая предустановка вступает в силу, и пользовательские опции цепочки фильтров, указанные ранее, забываются. Цепочка фильтров сравнима с конвейером в командной строке. При сжатии несжатый вход передаётся первому фильтру, выход которого передаётся следующему фильтру (если он есть). Выход последнего фильтра записывается в сжатый файл. Максимальное количество фильтров в цепочке - четыре, но обычно цепочка фильтров имеет всего один или два фильтра. Многие фильтры имеют ограничения на то, где они могут быть в цепочке фильтров: некоторые фильтры могут работать только как последний фильтр в цепочке, некоторые только как нефинальный, а некоторые работают в любой позиции цепочки. Это ограничение либо inherent к дизайну фильтра, либо существует, чтобы предотвратить проблемы безопасности. Пользовательскую цепочку фильтров можно указать двумя разными способами. Опции --filters=filters и --filters1=filters ... --filters9=filters позволяют указывать всю цепочку фильтров в одной опции с использованием синтаксиса строк фильтров liblzma. Альтернативно, цепочку фильтров можно указать, используя одну или более отдельных опций фильтров в порядке, в котором они должны быть в цепочке. То есть, порядок отдельных опций фильтров имеет значение! При декодировании необработанных потоков (--format=raw), цепочка фильтров должна быть указана в том же порядке, в котором она была указана при сжатии. Любые отдельные опции фильтров или опции предустановок, указанные до полной опции цепочки (--filters=filters), будут забыты. Отдельные фильтры, указанные после полной опции цепочки, сбросят цепочку фильтров. И полные, и отдельные опции фильтров принимают опции, специфические для фильтра, в виде списка, разделённого запятыми. Дополнительные запятые в опциях игнорируются. Каждой опции есть значение по умолчанию, поэтому укажите те, которые вы хотите изменить. Чтобы увидеть всю цепочку фильтров и опции, используйте xz -vv (то есть, используйте --verbose дважды). Это работает также для просмотра опций цепочки фильтров, используемых предустановками. --filters=filters Указать полную цепочку фильтров или предустановку в одной опции. Каждый фильтр может быть разделён пробелами или двумя дефисами (--). filters может потребоваться заключить в кавычки в командной строке оболочки, чтобы оно парсировалось как одна опция. Для обозначения опций используйте : или =. Предустановку можно предварить с - и за ней следовать ноль или более флагов. Единственный поддерживаемый флаг - e для применения тех же опций, что и --extreme. --filters1=filters ... --filters9=filters Указать до девяти дополнительных цепочек фильтров, которые можно использовать с --block-list. Например, при сжатии архива с исполняемыми файлами, за которыми следуют текстовые файлы, исполняемая часть может использовать цепочку фильтров с фильтром BCJ, а текстовая часть - только фильтр LZMA2. --filters-help Вывести справочное сообщение, описывающее, как указывать предустановки и пользовательские цепочки фильтров в опциях --filters и --filters1=filters ... --filters9=filters, и успешно выйти. --lzma1[=options] --lzma2[=options] Добавить фильтр LZMA1 или LZMA2 в цепочку фильтров. Эти фильтры могут быть использованы только как последний фильтр в цепочке. LZMA1 - устаревший фильтр, который поддерживается почти исключительно из-за устаревшего формата файла .lzma, который поддерживает только LZMA1. LZMA2 - обновлённая версия LZMA1 для устранения некоторых практических проблем LZMA1. Формат .xz использует LZMA2 и не поддерживает LZMA1. Скорость сжатия и соотношения LZMA1 и LZMA2 практически одинаковы. LZMA1 и LZMA2 делят один набор опций: preset=preset Сбросить все опции LZMA1 или LZMA2 на preset. Preset состоит из целого числа, за которым может следовать модификаторы предустановки в виде одиночной буквы. Целое число может быть от 0 до 9, соответствующее опциям командной строки -0 ... -9. Единственный поддерживаемый модификатор в настоящее время - e, который соответствует --extreme. Если preset не указан, значения опций LZMA1 или LZMA2 по умолчанию берутся из предустановки 6. dict=size Размер словаря (буфера истории) указывает, сколько байтов недавно обработанных несжатых данных хранится в памяти. Алгоритм пытается найти повторяющиеся последовательности байтов (совпадения) в несжатых данных и заменить их ссылками на данные, находящиеся в настоящее время в словаре. Чем больше словарь, тем выше шанс найти совпадение. Таким образом, увеличение размера словаря обычно улучшает соотношение сжатия, но словарь больше, чем несжатый файл, - трата памяти. Типичный размер словаря - от 64 KiB до 64 MiB. Минимум - 4 KiB. Максимум для сжатия в настоящее время - 1,5 GiB (1536 MiB). Декомпрессор уже поддерживает словари до одного байта меньше 4 GiB, что является максимумом для форматов потоков LZMA1 и LZMA2. Размер словаря и поисковик совпадений (mf) вместе определяют использование памяти энкодером LZMA1 или LZMA2. Для распаковки требуется тот же (или больший) размер словаря, что и при сжатии, таким образом, использование памяти декомпрессором определяется размером словаря, использованным при сжатии. Заголовки .xz хранят размер словаря как 2^n или 2^n + 2^(n-1), так что эти размеры немного предпочтительны для сжатия. Другие размеры будут округлены вверх при хранении в заголовках .xz. lc=lc Указать количество битов контекста литералов. Минимум - 0, максимум - 4; значение по умолчанию - 3. Кроме того, сумма lc и lp не должна превышать 4. Все байты, которые не могут быть закодированы как совпадения, кодируются как литералы. То есть, литералы - просто 8-битные байты, которые кодируются по одному. Литеральное кодирование предполагает, что высшие lc биты предыдущего несжатого байта коррелируют со следующим байтом. Например, в типичном английском тексте заглавная буква часто followed за строчной буквой, а строчная буква обычно followed за другой строчной буквой. В наборе символов US-ASCII высшие три бита - 010 для заглавных букв и 011 для строчных букв. Когда lc как минимум 3, литерное кодирование может использовать это свойство в несжатых данных. Значение по умолчанию (3) обычно хорошее. Если вы хотите максимальное сжатие, протестируйте lc=4. Иногда это помогает немного, а иногда ухудшает сжатие. Если оно ухудшает, протестируйте lc=2 тоже. lp=lp Указать количество битов позиции литералов. Минимум - 0, максимум - 4; значение по умолчанию - 0. lp влияет на то, какое выравнивание в несжатых данных предполагается при кодировании литералов. См. pb ниже для дополнительной информации о выравнивании. pb=pb Указать количество битов позиции. Минимум - 0, максимум - 4; значение по умолчанию - 2. pb влияет на то, какое выравнивание в несжатых данных предполагается в общем. Значение по умолчанию подразумевает четырёхбайтное выравнивание (2^pb=2^2=4), что часто бывает хорошим выбором, когда нет лучшей догадки. Когда выравнивание известно, установка pb соответственно может немного уменьшить размер файла. Например, с текстовыми файлами, имеющими однобайтовое выравнивание (US-ASCII, ISO-8859-*, UTF-8), установка pb=0 может немного улучшить сжатие. Для текста UTF-16 pb=1 - хороший выбор. Если выравнивание - нечётное число, как 3 байта, pb=0 может быть лучшим выбором. Даже если предполагаемое выравнивание можно скорректировать с pb и lp, LZMA1 и LZMA2 всё равно немного предпочитают 16-байтовое выравнивание. Стоит учитывать это при проектировании форматов файлов, которые, вероятно, будут часто сжиматься с LZMA1 или LZMA2. mf=mf Поисковик совпадений сильно влияет на скорость энкодера, использование памяти и соотношение сжатия. Обычно поисковики совпадений Hash Chain быстрее, чем Binary Tree. Значение по умолчанию зависит от предустановки: 0 использует hc3, 1–3 используют hc4, а остальные - bt4. Поддерживаются следующие поисковики совпадений. Формулы использования памяти ниже - грубые приближения, которые ближе всего к реальности, когда dict - степень двойки. hc3 Hash Chain с хэшированием 2- и 3-байтов Минимальное значение для nice: 3 Использование памяти: dict * 7.5 (если dict <= 16 MiB); dict * 5.5 + 64 MiB (если dict > 16 MiB) hc4 Hash Chain с хэшированием 2-, 3- и 4-байтов Минимальное значение для nice: 4 Использование памяти: dict * 7.5 (если dict <= 32 MiB); dict * 6.5 (если dict > 32 MiB) bt2 Binary Tree с хэшированием 2-байтов Минимальное значение для nice: 2 Использование памяти: dict * 9.5 bt3 Binary Tree с хэшированием 2- и 3-байтов Минимальное значение для nice: 3 Использование памяти: dict * 11.5 (если dict <= 16 MiB); dict * 9.5 + 64 MiB (если dict > 16 MiB) bt4 Binary Tree с хэшированием 2-, 3- и 4-байтов Минимальное значение для nice: 4 Использование памяти: dict * 11.5 (если dict <= 32 MiB); dict * 10.5 (если dict > 32 MiB) mode=mode Режим сжатия указывает метод анализа данных, производимых поисковиком совпадений. Поддерживаемые режимы - fast и normal. Значение по умолчанию - fast для предустановок 0–3 и normal для предустановок 4–9. Обычно fast используется с поисковиками совпадений Hash Chain и normal с Binary Tree. Это также то, что делают предустановки. nice=nice Указать, какая длина считается приятной для совпадения. Как только найдено совпадение длиной не менее nice байтов, алгоритм перестаёт искать возможные лучшие совпадения. nice может быть от 2 до 273 байтов. Более высокие значения склонны давать лучшее соотношение сжатия за счёт скорости. Значение по умолчанию зависит от предустановки. depth=depth Указать максимальную глубину поиска в поисковике совпадений. Значение по умолчанию - специальное значение 0, которое заставляет компрессор определять разумную глубину из mf и nice. Разумная глубина для Hash Chains - 4–100, а для Binary Trees - 16–1000. Использование очень высоких значений для depth может сделать энкодер крайне медленным для некоторых файлов. Избегайте установки depth выше 1000, если вы готовы прерывать сжатие, в случае если оно занимает слишком много времени. При декодировании необработанных потоков (--format=raw), LZMA2 needs только размер словаря. LZMA1 needs также lc, lp и pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Добавить фильтр ветвления/вызова/перехода (BCJ) в цепочку фильтров. Эти фильтры могут быть использованы только как нефинальный фильтр в цепочке. Фильтр BCJ преобразует относительные адреса в машинном коде в их абсолютные аналоги. Это не изменяет размер данных, но увеличивает избыточность, что может помочь LZMA2 создать файл .xz на 0–15 % меньше. Фильтры BCJ всегда обратимы, так что использование фильтра BCJ для неправильного типа данных не приведёт к потере данных, хотя может немного ухудшить соотношение сжатия. Фильтры BCJ очень быстрые и используют незначительное количество памяти. У этих фильтров BCJ известны проблемы, связанные соотношением сжатия: • Некоторые типы файлов, содержащие исполняемый код (например, объектные файлы, статические библиотеки и модули ядра Linux), имеют адреса в инструкциях, заполненные значениями заполнителя. Эти фильтры BCJ всё равно будут выполнять преобразование адреса, что сделает сжатие хуже для этих файлов. • Если фильтр BCJ применяется к архиву, возможно, что он сделает соотношение сжатия хуже, чем без использования фильтра BCJ. Например, если в архиве есть похожие или даже идентичные исполняемые файлы, фильтрация может сделать файлы менее похожими, и таким образом сжатие будет хуже. Содержимое нефайлов в том же архиве тоже может повлиять. На практике нужно попробовать с фильтром BCJ и без него, чтобы увидеть, что лучше в каждой ситуации. Разные наборы инструкций имеют разное выравнивание: исполняемый файл должен быть выровнен по кратному этого значения в входных данных, чтобы фильтр работал. Filter;Alignment;Notes x86;1;32-битный или 64-битный x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-байтовое выравнивание лучше PowerPC;4;Только big endian IA-64;16;Itanium SPARC;4; RISC-V;2; Поскольку отфильтрованные данные BCJ обычно сжимаются с LZMA2, соотношение сжатия может немного улучшиться, если опции LZMA2 установлены так, чтобы соответствовать выравниванию выбранного фильтра BCJ. Примеры: • Фильтр IA-64 имеет выравнивание 16 байтов, так что pb=4,lp=4,lc=0 хорошо работает с LZMA2 (2^4=16). • Код RISC-V имеет выравнивание 2 или 4 байта в зависимости от того, содержит ли файл 16-битные сжатые инструкции (расширение C). Когда используются 16-битные инструкции, pb=2,lp=1,lc=3 или pb=1,lp=1,lc=3 хорошо. Когда 16-битные инструкции отсутствуют, pb=2,lp=2,lc=2 - лучшее. readelf -h можно использовать, чтобы проверить, появляется ли "RVC" в строке "Flags". • ARM64 всегда имеет выравнивание 4 байта, так что pb=2,lp=2,lc=2 - лучшее. • Фильтр x86 - исключение. Обычно хорошо придерживаться значений по умолчанию LZMA2 (pb=2,lp=0,lc=3) при сжатии исполняемых файлов x86. Все фильтры BCJ поддерживают одни и те же опции: start=offset Указать начальный смещение, которое используется при преобразовании между относительными и абсолютными адресами. Смещение должно быть кратным выравниванию фильтра (см. таблицу выше). Значение по умолчанию - ноль. На практике значение по умолчанию хорошее; указание пользовательского смещения почти никогда не полезно. --delta[=options] Добавить фильтр Delta в цепочку фильтров. Фильтр Delta может быть использован только как нефинальный фильтр в цепочке. В настоящее время поддерживается только простое байт-вайз вычисление дельты. Это может быть полезно при сжатии, например, несжатых растровых изображений или несжатого PCM-аудио. Однако специализированные алгоритмы могут давать значительно лучшие результаты, чем Delta + LZMA2. Это верно особенно для аудио, которое сжимается быстрее и лучше, например, с flac(1). Поддерживаемые опции: dist=distance Указать расстояние вычисления дельты в байтах. distance должно быть от 1 до 256. Значение по умолчанию - 1. Например, с dist=2 и входом A1 B1 A2 B3 A3 B5 A4 B7 выход будет A1 B1 01 02 01 02 01 02. Другие опции -q, --quiet Подавлять предупреждения и уведомления. Укажите это дважды, чтобы подавлять ошибки тоже. Эта опция не влияет на код выхода. То есть, даже если предупреждение было подавлено, код выхода для указания предупреждения всё равно используется. -v, --verbose Быть подробным. Если стандартный вывод ошибок подключён к терминалу, xz отобразит индикатор прогресса. Указание --verbose дважды даст ещё более подробный вывод. Индикатор прогресса показывает следующую информацию: • Процент завершения показывается, если размер входного файла известен. То есть, процент не может быть показан в конвейерах. • Количество сжатых данных, произведённых (при сжатии) или потреблённых (при распаковке). • Количество несжатых данных, потреблённых (при сжатии) или произведённых (при распаковке). • Соотношение сжатия, которое рассчитывается путём деления количества обработанных сжатых данных на количество обработанных несжатых данных. • Скорость сжатия или распаковки. Это измеряется как количество несжатых данных, потреблённых (сжатие) или произведённых (распаковка) в секунду. Она показывается после того, как прошло несколько секунд с момента запуска xz обработки файла. • Прошедшее время в формате M:SS или H:MM:SS. • Оставшееся оценочное время показывается только, когда размер входного файла известен и прошло несколько секунд с момента запуска xz обработки файла. Время показывается в менее точном формате, который никогда не имеет двоеточий, например, 2 min 30 s. Когда стандартный вывод ошибок не является терминалом, --verbose заставит xz вывести имя файла, сжатый размер, несжатый размер, соотношение сжатия и, возможно, скорость и прошедшее время в одной строке в стандартный вывод ошибок после сжатия или распаковки файла. Скорость и прошедшее время включаются только, когда операция заняла хотя бы несколько секунд. Если операция не завершилась, например, из-за прерывания пользователем, также выводится процент завершения, если размер входного файла известен. -Q, --no-warn Не устанавливать код выхода на 2, даже если обнаружено условие, заслуживающее предупреждения. Эта опция не влияет на уровень подробности, так что для подавления вывода предупреждений и не изменения кода выхода нужно использовать как --quiet, так и --no-warn. --robot Выводить сообщения в формате, удобном для разбора машинами. Это предназначено для облегчения написания фронтендов, которые хотят использовать xz вместо liblzma, что может быть в случае с различными скриптами. Вывод с этой опцией включён предназначен для стабильности между релизами xz. См. раздел РЕЖИМ РОБОТА для деталей. --info-memory Вывести в человекочитаемом формате, сколько физической памяти (ОЗУ) и сколько процессорных потоков, по мнению xz, имеет система, и лимиты использования памяти для сжатия и распаковки, и успешно выйти. -h, --help Вывести справочное сообщение, описывающее наиболее часто используемые опции, и успешно выйти. -H, --long-help Вывести справочное сообщение, описывающее все функции xz, и успешно выйти. -V, --version Вывести номер версии xz и liblzma в человекочитаемом формате. Для получения вывода, удобного для разбора машинами, укажите --robot перед --version. РЕЖИМ РОБОТА Режим робота активируется с опцией --robot. Он делает вывод xz проще для разбора другими программами. В настоящее время --robot поддерживается только вместе с --list, --filters-help, --info-memory и --version. В будущем он будет поддерживаться для сжатия и распаковки. Режим списка xz --robot --list использует вывод, разделённый табуляцией. Первый столбец каждой строки содержит строку, которая указывает тип информации, найденной на этой строке: name Это всегда первая строка при начале списка файла. Второй столбец на строке - имя файла. file Эта строка содержит общую информацию о файле .xz. Эта строка всегда выводится после строки name. stream Эта строка используется только, когда указан --verbose. Здесь столько строк stream, сколько потоков в файле .xz. block Эта строка используется только, когда указан --verbose. Здесь столько строк block, сколько блоков в файле .xz. Строки block показываются после всех строк stream; разные типы строк не перемежаются. summary Этот тип строки используется только, когда указан --verbose дважды. Эта строка выводится после всех строк block. Как и строка file, строка summary содержит общую информацию о файле .xz. totals Эта строка всегда последняя строка вывода списка. Она показывает общие счётчики и размеры. Столбцы строк file: 2. Количество потоков в файле 3. Общее количество блоков в потоке(ах) 4. Сжатый размер файла 5. Несжатый размер файла 6. Соотношение сжатия, например, 0.123. Если соотношение превышает 9.999, выводятся три тире (---) вместо соотношения. 7. Список имён проверок целостности, разделённый запятыми. Для известных типов проверок используются следующие строки: None, CRC32, CRC64 и SHA-256. Для неизвестных типов проверок используется Unknown-N, где N - ID проверки в десятичном виде (одна или две цифры). 8. Общий размер заполнения потока в файле Столбцы строк stream: 2. Номер потока (первый поток - 1) 3. Количество блоков в потоке 4. Сжатый начальный смещение 5. Несжатый начальный смещение 6. Сжатый размер (не включает заполнение потока) 7. Несжатый размер 8. Соотношение сжатия 9. Имя проверки целостности 10. Размер заполнения потока Столбцы строк block: 2. Номер потока, содержащего этот блок 3. Номер блока относительно начала потока (первый блок - 1) 4. Номер блока относительно начала файла 5. Сжатый начальный смещение относительно начала файла 6. Несжатый начальный смещение относительно начала файла 7. Общий сжатый размер блока (включает заголовки) 8. Несжатый размер 9. Соотношение сжатия 10. Имя проверки целостности Если указан --verbose дважды, в строках block добавляются дополнительные столбцы. Эти не отображаются с одним --verbose, потому что получение этой информации требует многих поисков и, следовательно, может быть медленно: 11. Значение проверки целостности в шестнадцатеричном формате 12. Размер заголовка блока 13. Флаги блока: c указывает, что сжатый размер присутствует, а u указывает, что несжатый размер присутствует. Если флаг не установлен, выводится дефис (-) для поддержания фиксированной длины строки. Новые флаги могут быть добавлены в конец строки в будущем. 14. Размер фактических сжатых данных в блоке (это исключает заголовок блока, заполнение блока и поля проверки) 15. Количество памяти (в байтах), требуемое для распаковки этого блока с этой версией xz 16. Цепочка фильтров. Обратите внимание, что большинство опций, использованных во время сжатия, не могут быть известны, поскольку только опции, которые необходимы для распаковки, хранятся в заголовках .xz. Столбцы строк summary: 2. Количество памяти (в байтах), требуемое для распаковки этого файла с этой версией xz 3. yes или no, указывающее, есть ли у всех заголовков блоков как сжатый, так и несжатый размер, хранящийся в них С версии xz 5.1.2alpha: 4. Минимальная версия xz, требуемая для распаковки файла Столбцы строки totals: 2. Количество потоков 3. Количество блоков 4. Сжатый размер 5. Несжатый размер 6. Среднее соотношение сжатия 7. Список имён проверок целостности, которые присутствовали в файлах, разделённый запятыми 8. Размер заполнения потока 9. Количество файлов. Это здесь, чтобы сохранить порядок предыдущих столбцов таким же, как в строках file. Если указан --verbose дважды, в строке totals добавляются дополнительные столбцы: 10. Максимальное количество памяти (в байтах), требуемое для распаковки файлов с этой версией xz 11. yes или no, указывающее, есть ли у всех заголовков блоков как сжатый, так и несжатый размер, хранящийся в них С версии xz 5.1.2alpha: 12. Минимальная версия xz, требуемая для распаковки файла Будущие версии могут добавить новые типы строк, и новые столбцы могут быть добавлены к существующим типам строк, но существующие столбцы не будут изменены. Помощь по фильтрам xz --robot --filters-help выводит поддерживаемые фильтры в следующем формате: filter:option=<value>,option=<value>... filter Имя фильтра option Имя опции, специфичной для фильтра value Диапазоны значений чисел отображаются как <min-max>. Выборы значений строк показываются в < > и разделяются символом |. Каждый фильтр выводится на своей строке. Информация о лимите памяти xz --robot --info-memory выводит одну строку с несколькими столбцами, разделёнными табуляцией: 1. Общий объём физической памяти (ОЗУ) в байтах. 2. Лимит использования памяти для сжатия в байтах (--memlimit-compress). Специальное значение 0 указывает на значение по умолчанию, которое для однонитевого режима то же, что и отсутствие лимита. 3. Лимит использования памяти для распаковки в байтах (--memlimit-decompress). Специальное значение 0 указывает на значение по умолчанию, которое для однонитевого режима то же, что и отсутствие лимита. 4. С версии xz 5.3.4alpha: Использование памяти для многопоточной распаковки в байтах (--memlimit-mt-decompress). Это никогда не ноль, потому что системно-специфическое значение по умолчанию, показанное в столбце 5, используется, если лимит не указан явно. Это также никогда не больше значения в столбце 3, даже если указано большее значение с --memlimit-mt-decompress. 5. С версии xz 5.3.4alpha: Системно-специфическое значение лимита использования памяти по умолчанию, которое используется для ограничения количества потоков при сжатии с автоматическим количеством потоков (--threads=0) и без указанного лимита использования памяти (--memlimit-compress). Это также используется как значение по умолчанию для --memlimit-mt-decompress. 6. С версии xz 5.3.4alpha: Количество доступных процессорных потоков. В будущем вывод xz --robot --info-memory может иметь больше столбцов, но никогда не больше одной строки. Версия xz --robot --version выводит номер версии xz и liblzma в следующем формате: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Основная версия. YYY Дополнительная версия. Чётные числа стабильны. Нечётные числа - альфа- или бета-версии. ZZZ Уровень патча для стабильных релизов или просто счётчик для версий разработки. S Стабильность. 0 - альфа, 1 - бета, и 2 - стабильная. S должно быть всегда 2, когда YYY чётное. XYYYZZZS одинаковы в обоих строках, если xz и liblzma из одного релиза XZ Utils. Примеры: 4.999.9beta - 49990091 и 5.0.0 - 50000002. КОД ВЫХОДА 0 Всё в порядке. 1 Произошла ошибка. 2 Произошло что-то, заслуживающее предупреждения, но реальных ошибок не произошло. Уведомления (не предупреждения или ошибки), выведенные в стандартный вывод ошибок, не влияют на код выхода. ОКРУЖЕНИЕ xz парсит списки опций, разделённые пробелами, из переменных окружения XZ_DEFAULTS и XZ_OPT, в этом порядке, перед разбором опций из командной строки. Обратите внимание, что из переменных окружения парсятся только опции; все нефции тихо игнорируются. Разбор выполняется с getopt_long(3), которая используется также для аргументов командной строки. XZ_DEFAULTS Пользовательские или системные опции по умолчанию. Обычно это устанавливается в скрипте инициализации оболочки для включения лимитера использования памяти xz по умолчанию. Исключая скрипты инициализации оболочки и подобные специальные случаи, скрипты никогда не должны устанавливать или сбрасывать XZ_DEFAULTS. XZ_OPT Это для передачи опций xz, когда невозможно установить опции напрямую в командной строке xz. Это случай, когда xz запускается скриптом или инструментом, например, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Сценарии могут использовать XZ_OPT, например, для установки опций сжатия, специфичных для сценария. Всё равно рекомендуется позволить пользователям переопределять XZ_OPT, если это разумно. Например, в сценариях sh(1) можно использовать что-то вроде этого: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT СОВМЕСТИМОСТЬ С LZMA UTILS Синтаксис командной строки xz практически является надмножеством lzma, unlzma и lzcat из LZMA Utils 4.32.x. В большинстве случаев возможно заменить LZMA Utils на XZ Utils без нарушения существующих сценариев. Однако есть некоторые несоответствия, которые иногда могут вызвать проблемы. Уровни предустановок сжатия Нумерация уровней предустановок сжатия не идентична в xz и LZMA Utils. Самое важное различие - как размеры словарей сопоставляются с разными предустановками. Размер словаря примерно равен использованию памяти декомпрессором. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB Различия размеров словарей влияют и на использование памяти компрессором, но есть некоторые другие различия между LZMA Utils и XZ Utils, которые делают разницу ещё больше: Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB Значение предустановки по умолчанию в LZMA Utils - -7, в то время как в XZ Utils - -6, так что оба используют словарь 8 MiB по умолчанию. Потоковые и непотоковые файлы .lzma Несжатый размер файла может храниться в заголовке .lzma. LZMA Utils делает это при сжатии обычных файлов. Альтернатива - отметить, что несжатый размер неизвестен, и использовать маркер конца полезной нагрузки, чтобы указать, где декомпрессор должен остановиться. LZMA Utils использует этот метод, когда несжатый размер неизвестен, что является случаем, например, в конвейерах. xz поддерживает распаковку файлов .lzma с маркером конца полезной нагрузки или без него, но все файлы .lzma, созданные xz, будут использовать маркер конца полезной нагрузки и иметь несжатый размер, отмеченный как неизвестный в заголовке .lzma. Это может быть проблемой в некоторых необычных ситуациях. Например, декомпрессор .lzma в встроенном устройстве может работать только с файлами, у которых известен несжатый размер. Если вы столкнётесь с этой проблемой, вам нужно использовать LZMA Utils или LZMA SDK для создания файлов .lzma с известным несжатым размером. Неподдерживаемые файлы .lzma Формат .lzma позволяет значения lc до 8 и lp до 4. LZMA Utils может распаковывать файлы с любыми lc и lp, но всегда создаёт файлы с lc=3 и lp=0. Создание файлов с другими lc и lp возможно с xz и с LZMA SDK. Реализация фильтра LZMA1 в liblzma требует, чтобы сумма lc и lp не превышала 4. Таким образом, файлы .lzma, которые превышают это ограничение, не могут быть распакованы с xz. LZMA Utils создаёт только файлы .lzma, у которых размер словаря - 2^n (степень двойки), но принимает файлы с любым размером словаря. liblzma принимает только файлы .lzma, у которых размер словаря - 2^n или 2^n + 2^(n-1). Это для уменьшения ложных срабатываний при обнаружении файлов .lzma. Эти ограничения не должны быть проблемой на практике, поскольку практически все файлы .lzma были сжаты с настройками, которые liblzma примет. Завершающий мусор При распаковке LZMA Utils тихо игнорируют всё после первого потока .lzma. В большинстве ситуаций это - ошибка. Это также означает, что LZMA Utils не поддерживают распаковку конкатенированных файлов .lzma. Если после первого потока .lzma остались данные, xz считает файл повреждённым, если не указан --single-stream. Это может нарушить неоднозначные скрипты, которые предполагали, что завершающий мусор игнорируется. ПРИМЕЧАНИЯ Сжатый вывод может варьироваться Точный сжатый вывод, произведённый из одного и того же несжатого входного файла, может варьироваться между версиями XZ Utils, даже если опции сжатия идентичны. Это потому, что энкодер может быть улучшен (быстрее или лучше сжатие) без влияния на формат файла. Вывод может варьироваться даже между разными сборками одной и той же версии XZ Utils, если используются разные опции сборки. Вышеизложенное означает, что как только будет реализован --rsyncable, результирующие файлы не обязательно будут rsyncable, если оба старый и новый файлы были сжаты с одной версией xz. Эта проблема может быть решена, если часть реализации энкодера будет заморожена, чтобы сохранить rsyncable вывод стабильным между версиями xz. Встроенные декомпрессоры .xz Встроенные реализации декомпрессоров .xz, такие как XZ Embedded, не обязательно поддерживают файлы, созданные с типами проверок целостности, отличными от none и crc32. Поскольку значение по умолчанию - --check=crc64, вам нужно использовать --check=none или --check=crc32 при создании файлов для встроенных систем. За пределами встроенных систем все декомпрессоры формата .xz поддерживают все типы проверок или, по крайней мере, способны распаковывать файл без проверки целостности, если этот конкретный тип проверки не поддерживается. XZ Embedded поддерживает фильтры BCJ, но только с смещением начала по умолчанию. ПРИМЕРЫ Основы Сжать файл foo в foo.xz с использованием уровня сжатия по умолчанию (-6) и удалить foo, если сжатие успешно: xz foo Распаковать bar.xz в bar и не удалять bar.xz, даже если распаковка успешна: xz -dk bar.xz Создать baz.tar.xz с предустановкой -4e (-4 --extreme), которая медленнее, чем значение по умолчанию -6, но требует меньше памяти для сжатия и распаковки (48 MiB и 5 MiB соответственно): tar cf - baz | xz -4e > baz.tar.xz Смесь сжатых и несжатых файлов может быть распакована в стандартный вывод с одной командой: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Параллельное сжатие многих файлов В GNU и *BSD find(1) и xargs(1) можно использовать для параллельного сжатия многих файлов: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 Опция -P xargs(1) устанавливает количество параллельных процессов xz. Лучшее значение для опции -n зависит от количества файлов, подлежащих сжатию. Если файлов всего несколько, значение, вероятно, должно быть 1; с десятками тысяч файлов 100 или даже больше может быть подходящим, чтобы уменьшить количество процессов xz, которые xargs(1) в конечном итоге создаст. Опция -T1 для xz здесь, чтобы заставить его работать в однонитевом режиме, поскольку xargs(1) используется для управления количеством параллелизации. Режим робота Рассчитать, сколько байтов сэкономлено в сумме после сжатия нескольких файлов: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' Сценарий может захотеть знать, что он использует достаточно новую версию xz. Следующий сценарий sh(1) проверяет, что номер версии инструмента xz как минимум 5.0.0. Этот метод совместим со старыми бета-версиями, которые не поддерживали опцию --robot: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Пользовательские цепочки фильтров компрессора Самое простое использование пользовательских цепочек фильтров - настройка предустановки LZMA2. Это может быть полезно, потому что предустановки охватывают только подмножество потенциально полезных комбинаций настроек сжатия. Столбцы CompCPU таблиц из описаний опций -0 ... -9 и --extreme полезны при настройке предустановок LZMA2. Вот релевантные части, собранные из этих двух таблиц: Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 Если вы знаете, что файл требует довольно большого словаря (например, 32 MiB), чтобы сжиматься хорошо, но вы хотите сжимать его быстрее, чем xz -8, предустановку с низким значением CompCPU (например, 1) можно изменить, чтобы использовать больший словарь: xz --lzma2=preset=1,dict=32MiB foo.tar С некоторыми файлами вышеуказанная команда может быть быстрее, чем xz -6, при значительно лучшем сжатии. Однако стоит подчеркнуть, что только некоторые файлы受益 от большого словаря, сохраняя значение CompCPU низким. Самая очевидная ситуация, где большой словарь может сильно помочь, - архив, содержащий очень похожие файлы объёмом как минимум несколько мегабайт каждый. Размер словаря должен быть значительно больше, чем любой индивидуальный файл, чтобы позволить LZMA2 полностью использовать сходства между последовательными файлами. Если очень высокое использование памяти компрессора и декомпрессора приемлемо, и файл, подлежащий сжатию, имеет размер как минимум несколько сотен мегабайт, может быть полезно использовать даже больший словарь, чем 64 MiB, который использует xz -9: xz -vv --lzma2=dict=192MiB big_foo.tar Использование -vv (--verbose --verbose), как в примере выше, может быть полезным, чтобы увидеть требования к памяти компрессора и декомпрессора. Помните, что использование словаря больше, чем размер несжатого файла, - трата памяти, так что вышеуказанная команда бесполезна для малых файлов. Иногда время сжатия не имеет значения, но использование памяти декомпрессором должно быть сохранено низким, например, чтобы сделать возможной распаковку файла на встроенной системе. Следующая команда использует -6e (-6 --extreme) как основу и устанавливает словарь только на 64 KiB. Получившийся файл может быть распакован с XZ Embedded (вот почему там --check=crc32) с использованием около 100 KiB памяти. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo Если вы хотите выжать как можно больше байтов, корректировка количества битов контекста литералов (lc) и количества битов позиции (pb) иногда может помочь. Корректировка количества битов позиции литералов (lp) может помочь тоже, но обычно lc и pb важнее. Например, архив исходного кода в основном содержит текст US-ASCII, так что что-то вроде следующего может дать немного (как 0,1 %) меньший файл, чем xz -6e (попробуйте также без lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Использование другого фильтра вместе с LZMA2 может улучшить сжатие для определённых типов файлов. Например, чтобы сжать общую библиотеку x86-32 или x86-64 с использованием фильтра BCJ x86: xz --x86 --lzma2 libfoo.so Обратите внимание, что порядок опций фильтров имеет значение. Если --x86 указан после --lzma2, xz выдаст ошибку, потому что после LZMA2 не может быть других фильтров, и также потому, что фильтр BCJ x86 не может быть использован как последний фильтр в цепочке. Фильтр Delta вместе с LZMA2 может дать хорошие результаты с растровыми изображениями. Он обычно должен превосходить PNG, который имеет несколько более продвинутых фильтров, чем простой дельта, но использует Deflate для фактического сжатия. Изображение должно быть сохранено в несжатом формате, например, как несжатый TIFF. Параметр distance фильтра Delta устанавливается, чтобы соответствовать количеству байтов на пиксель в изображении. Например, 24-битное растровое изображение RGB needs dist=3, и также хорошо передать pb=0 в LZMA2, чтобы учесть трёхбайтное выравнивание: xz --delta=dist=3 --lzma2=pb=0 foo.tiff Если несколько изображений помещены в один архив (например, .tar), фильтр Delta будет работать и с этим, пока все изображения имеют одинаковое количество байтов на пиксель. СМОТРИТЕ ТАКЖЕ xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html>
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Compress or decompress .xz and .lzma files SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz is equivalent to xz --decompress. xzcat is equivalent to xz --decompress --stdout. lzma is equivalent to xz --format=lzma. unlzma is equivalent to xz --format=lzma --decompress. lzcat is equivalent to xz --format=lzma --decompress --stdout. When writing scripts that need to decompress files, it is recommended to always use the name xz with appropriate arguments (xz -d or xz -dc) instead of the names unxz and xzcat. DESCRIPTION xz is a general-purpose data compression tool with command line syntax similar to gzip(1) and bzip2(1). The native file format is the .xz format, but the legacy .lzma format used by LZMA Utils and raw com‐ pressed streams with no container format headers are also supported. In addition, decompression of the .lz format used by lzip is supported. xz compresses or decompresses each file according to the selected oper‐ ation mode. If no files are given or file is -, xz reads from standard input and writes the processed data to standard output. xz will refuse (display an error and skip the file) to write compressed data to stan‐ dard output if it is a terminal. Similarly, xz will refuse to read compressed data from standard input if it is a terminal. Unless --stdout is specified, files other than - are written to a new file whose name is derived from the source file name: • When compressing, the suffix of the target file format (.xz or .lzma) is appended to the source filename to get the target file‐ name. • When decompressing, the .xz, .lzma, or .lz suffix is removed from the filename to get the target filename. xz also recognizes the suffixes .txz and .tlz, and replaces them with the .tar suffix. If the target file already exists, an error is displayed and the file is skipped. Unless writing to standard output, xz will display a warning and skip the file if any of the following applies: • File is not a regular file. Symbolic links are not followed, and thus they are not considered to be regular files. • File has more than one hard link. • File has setuid, setgid, or sticky bit set. • The operation mode is set to compress and the file already has a suffix of the target file format (.xz or .txz when compressing to the .xz format, and .lzma or .tlz when compressing to the .lzma for‐ mat). • The operation mode is set to decompress and the file doesn't have a suffix of any of the supported file formats (.xz, .txz, .lzma, .tlz, or .lz). After successfully compressing or decompressing the file, xz copies the owner, group, permissions, access time, and modification time from the source file to the target file. If copying the group fails, the per‐ missions are modified so that the target file doesn't become accessible to users who didn't have permission to access the source file. xz doesn't support copying other metadata like access control lists or ex‐ tended attributes yet. Once the target file has been successfully closed, the source file is removed unless --keep was specified. The source file is never removed if the output is written to standard output or if an error occurs. Sending SIGINFO or SIGUSR1 to the xz process makes it print progress information to standard error. This has only limited use since when standard error is a terminal, using --verbose will display an automati‐ cally updating progress indicator. Memory usage The memory usage of xz varies from a few hundred kilobytes to several gigabytes depending on the compression settings. The settings used when compressing a file determine the memory requirements of the decom‐ pressor. Typically the decompressor needs 5 % to 20 % of the amount of memory that the compressor needed when creating the file. For example, decompressing a file created with xz -9 currently requires 65 MiB of memory. Still, it is possible to have .xz files that require several gigabytes of memory to decompress. Especially users of older systems may find the possibility of very large memory usage annoying. To prevent uncomfortable surprises, xz has a built-in memory usage limiter, which is disabled by default. While some operating systems provide ways to limit the memory usage of processes, relying on it wasn't deemed to be flexible enough (for exam‐ ple, using ulimit(1) to limit virtual memory tends to cripple mmap(2)). The memory usage limiter can be enabled with the command line option --memlimit=limit. Often it is more convenient to enable the limiter by default by setting the environment variable XZ_DEFAULTS, for example, XZ_DEFAULTS=--memlimit=150MiB. It is possible to set the limits sepa‐ rately for compression and decompression by using --memlimit-com‐ press=limit and --memlimit-decompress=limit. Using these two options outside XZ_DEFAULTS is rarely useful because a single run of xz cannot do both compression and decompression and --memlimit=limit (or -M limit) is shorter to type on the command line. If the specified memory usage limit is exceeded when decompressing, xz will display an error and decompressing the file will fail. If the limit is exceeded when compressing, xz will try to scale the settings down so that the limit is no longer exceeded (except when using --for‐ mat=raw or --no-adjust). This way the operation won't fail unless the limit is very small. The scaling of the settings is done in steps that don't match the compression level presets, for example, if the limit is only slightly less than the amount required for xz -9, the settings will be scaled down only a little, not all the way down to xz -8. Concatenation and padding with .xz files It is possible to concatenate .xz files as is. xz will decompress such files as if they were a single .xz file. It is possible to insert padding between the concatenated parts or af‐ ter the last part. The padding must consist of null bytes and the size of the padding must be a multiple of four bytes. This can be useful, for example, if the .xz file is stored on a medium that measures file sizes in 512-byte blocks. Concatenation and padding are not allowed with .lzma files or raw streams. OPTIONS Integer suffixes and special values In most places where an integer argument is expected, an optional suf‐ fix is supported to easily indicate large integers. There must be no space between the integer and the suffix. KiB Multiply the integer by 1,024 (2^10). Ki, k, kB, K, and KB are accepted as synonyms for KiB. MiB Multiply the integer by 1,048,576 (2^20). Mi, m, M, and MB are accepted as synonyms for MiB. GiB Multiply the integer by 1,073,741,824 (2^30). Gi, g, G, and GB are accepted as synonyms for GiB. The special value max can be used to indicate the maximum integer value supported by the option. Operation mode If multiple operation mode options are given, the last one takes ef‐ fect. -z, --compress Compress. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, unxz implies --decompress). After successful compression, the source file is removed unless writing to standard output or --keep was specified. -d, --decompress, --uncompress Decompress. After successful decompression, the source file is removed unless writing to standard output or --keep was speci‐ fied. -t, --test Test the integrity of compressed files. This option is equiva‐ lent to --decompress --stdout except that the decompressed data is discarded instead of being written to standard output. No files are created or removed. -l, --list Print information about compressed files. No uncompressed out‐ put is produced, and no files are created or removed. In list mode, the program cannot read the compressed data from standard input or from other unseekable sources. The default listing shows basic information about files, one file per line. To get more detailed information, use also the --verbose option. For even more information, use --verbose twice, but note that this may be slow, because getting all the extra information requires many seeks. The width of verbose output exceeds 80 characters, so piping the output to, for exam‐ ple, less -S may be convenient if the terminal isn't wide enough. The exact output may vary between xz versions and different lo‐ cales. For machine-readable output, --robot --list should be used. Operation modifiers -k, --keep Don't delete the input files. Since xz 5.2.6, this option also makes xz compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. In earlier versions this was only done with --force. -f, --force This option has several effects: • If the target file already exists, delete it before compress‐ ing or decompressing. • Compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. • When used with --decompress --stdout and xz cannot recognize the type of the source file, copy the source file as is to standard output. This allows xzcat --force to be used like cat(1) for files that have not been compressed with xz. Note that in future, xz might support new compressed file formats, which may make xz decompress more types of files instead of copying them as is to standard output. --format=format can be used to restrict xz to decompress only a single file for‐ mat. -c, --stdout, --to-stdout Write the compressed or decompressed data to standard output in‐ stead of a file. This implies --keep. --single-stream Decompress only the first .xz stream, and silently ignore possi‐ ble remaining input data following the stream. Normally such trailing garbage makes xz display an error. xz never decompresses more than one stream from .lzma files or raw streams, but this option still makes xz ignore the possible trailing data after the .lzma file or raw stream. This option has no effect if the operation mode is not --decom‐ press or --test. --no-sparse Disable creation of sparse files. By default, if decompressing into a regular file, xz tries to make the file sparse if the de‐ compressed data contains long sequences of binary zeros. It also works when writing to standard output as long as standard output is connected to a regular file and certain additional conditions are met to make it safe. Creating sparse files may save disk space and speed up the decompression by reducing the amount of disk I/O. -S .suf, --suffix=.suf When compressing, use .suf as the suffix for the target file in‐ stead of .xz or .lzma. If not writing to standard output and the source file already has the suffix .suf, a warning is dis‐ played and the file is skipped. When decompressing, recognize files with the suffix .suf in ad‐ dition to files with the .xz, .txz, .lzma, .tlz, or .lz suffix. If the source file has the suffix .suf, the suffix is removed to get the target filename. When compressing or decompressing raw streams (--format=raw), the suffix must always be specified unless writing to standard output, because there is no default suffix for raw streams. --files[=file] Read the filenames to process from file; if file is omitted, filenames are read from standard input. Filenames must be ter‐ minated with the newline character. A dash (-) is taken as a regular filename; it doesn't mean standard input. If filenames are given also as command line arguments, they are processed be‐ fore the filenames read from file. --files0[=file] This is identical to --files[=file] except that each filename must be terminated with the null character. Basic file format and compression options -F format, --format=format Specify the file format to compress or decompress: auto This is the default. When compressing, auto is equiva‐ lent to xz. When decompressing, the format of the input file is automatically detected. Note that raw streams (created with --format=raw) cannot be auto-detected. xz Compress to the .xz file format, or accept only .xz files when decompressing. lzma, alone Compress to the legacy .lzma file format, or accept only .lzma files when decompressing. The alternative name alone is provided for backwards compatibility with LZMA Utils. lzip Accept only .lz files when decompressing. Compression is not supported. The .lz format version 0 and the unextended version 1 are supported. Version 0 files were produced by lzip 1.3 and older. Such files aren't common but may be found from file archives as a few source packages were released in this format. People might have old personal files in this format too. Decompression support for the format version 0 was removed in lzip 1.18. lzip 1.4 and later create files in the format version 1. The sync flush marker extension to the format version 1 was added in lzip 1.6. This extension is rarely used and isn't supported by xz (diagnosed as corrupt input). raw Compress or uncompress a raw stream (no headers). This is meant for advanced users only. To decode raw streams, you need use --format=raw and explicitly specify the fil‐ ter chain, which normally would have been stored in the container headers. -C check, --check=check Specify the type of the integrity check. The check is calcu‐ lated from the uncompressed data and stored in the .xz file. This option has an effect only when compressing into the .xz format; the .lzma format doesn't support integrity checks. The integrity check (if any) is verified when the .xz file is decom‐ pressed. Supported check types: none Don't calculate an integrity check at all. This is usu‐ ally a bad idea. This can be useful when integrity of the data is verified by other means anyway. crc32 Calculate CRC32 using the polynomial from IEEE-802.3 (Ethernet). crc64 Calculate CRC64 using the polynomial from ECMA-182. This is the default, since it is slightly better than CRC32 at detecting damaged files and the speed difference is neg‐ ligible. sha256 Calculate SHA-256. This is somewhat slower than CRC32 and CRC64. Integrity of the .xz headers is always verified with CRC32. It is not possible to change or disable it. --ignore-check Don't verify the integrity check of the compressed data when de‐ compressing. The CRC32 values in the .xz headers will still be verified normally. Do not use this option unless you know what you are doing. Pos‐ sible reasons to use this option: • Trying to recover data from a corrupt .xz file. • Speeding up decompression. This matters mostly with SHA-256 or with files that have compressed extremely well. It's rec‐ ommended to not use this option for this purpose unless the file integrity is verified externally in some other way. -0 ... -9 Select a compression preset level. The default is -6. If mul‐ tiple preset levels are specified, the last one takes effect. If a custom filter chain was already specified, setting a com‐ pression preset level clears the custom filter chain. The differences between the presets are more significant than with gzip(1) and bzip2(1). The selected compression settings determine the memory requirements of the decompressor, thus us‐ ing a too high preset level might make it painful to decompress the file on an old system with little RAM. Specifically, it's not a good idea to blindly use -9 for everything like it often is with gzip(1) and bzip2(1). -0 ... -3 These are somewhat fast presets. -0 is sometimes faster than gzip -9 while compressing much better. The higher ones often have speed comparable to bzip2(1) with compa‐ rable or better compression ratio, although the results depend a lot on the type of data being compressed. -4 ... -6 Good to very good compression while keeping decompressor memory usage reasonable even for old systems. -6 is the default, which is usually a good choice for distributing files that need to be decompressible even on systems with only 16 MiB RAM. (-5e or -6e may be worth considering too. See --extreme.) -7 ... -9 These are like -6 but with higher compressor and decom‐ pressor memory requirements. These are useful only when compressing files bigger than 8 MiB, 16 MiB, and 32 MiB, respectively. On the same hardware, the decompression speed is approximately a constant number of bytes of compressed data per second. In other words, the better the compression, the faster the decom‐ pression will usually be. This also means that the amount of uncompressed output produced per second can vary a lot. The following table summarises the features of the presets: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Column descriptions: • DictSize is the LZMA2 dictionary size. It is waste of memory to use a dictionary bigger than the size of the uncompressed file. This is why it is good to avoid using the presets -7 ... -9 when there's no real need for them. At -6 and lower, the amount of memory wasted is usually low enough to not mat‐ ter. • CompCPU is a simplified representation of the LZMA2 settings that affect compression speed. The dictionary size affects speed too, so while CompCPU is the same for levels -6 ... -9, higher levels still tend to be a little slower. To get even slower and thus possibly better compression, see --extreme. • CompMem contains the compressor memory requirements in the single-threaded mode. It may vary slightly between xz ver‐ sions. • DecMem contains the decompressor memory requirements. That is, the compression settings determine the memory require‐ ments of the decompressor. The exact decompressor memory us‐ age is slightly more than the LZMA2 dictionary size, but the values in the table have been rounded up to the next full MiB. Memory requirements of the multi-threaded mode are significantly higher than that of the single-threaded mode. With the default value of --block-size, each thread needs 3*3*DictSize plus Comp‐ Mem or DecMem. For example, four threads with preset -6 needs 660–670 MiB of memory. -e, --extreme Use a slower variant of the selected compression preset level (-0 ... -9) to hopefully get a little bit better compression ra‐ tio, but with bad luck this can also make it worse. Decompres‐ sor memory usage is not affected, but compressor memory usage increases a little at preset levels -0 ... -3. Since there are two presets with dictionary sizes 4 MiB and 8 MiB, the presets -3e and -5e use slightly faster settings (lower CompCPU) than -4e and -6e, respectively. That way no two presets are identical. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB For example, there are a total of four presets that use 8 MiB dictionary, whose order from the fastest to the slowest is -5, -6, -5e, and -6e. --fast --best These are somewhat misleading aliases for -0 and -9, respec‐ tively. These are provided only for backwards compatibility with LZMA Utils. Avoid using these options. --block-size=size When compressing to the .xz format, split the input data into blocks of size bytes. The blocks are compressed independently from each other, which helps with multi-threading and makes lim‐ ited random-access decompression possible. This option is typi‐ cally used to override the default block size in multi-threaded mode, but this option can be used in single-threaded mode too. In multi-threaded mode about three times size bytes will be al‐ located in each thread for buffering input and output. The de‐ fault size is three times the LZMA2 dictionary size or 1 MiB, whichever is more. Typically a good value is 2–4 times the size of the LZMA2 dictionary or at least 1 MiB. Using size less than the LZMA2 dictionary size is waste of RAM because then the LZMA2 dictionary buffer will never get fully used. In multi-threaded mode, the sizes of the blocks are stored in the block headers. This size information is required for multi-threaded decompres‐ sion. In single-threaded mode no block splitting is done by default. Setting this option doesn't affect memory usage. No size infor‐ mation is stored in block headers, thus files created in single- threaded mode won't be identical to files created in multi- threaded mode. The lack of size information also means that xz won't be able decompress the files in multi-threaded mode. --block-list=items When compressing to the .xz format, start a new block with an optional custom filter chain after the given intervals of uncom‐ pressed data. The items are a comma-separated list. Each item consists of an optional filter chain number between 0 and 9 followed by a colon (:) and a required size of uncompressed data. Omitting an item (two or more consecutive commas) is a shorthand to use the size and filters of the previous item. If the input file is bigger than the sum of the sizes in items, the last item is repeated until the end of the file. A special value of 0 may be used as the last size to indicate that the rest of the file should be encoded as a single block. An alternative filter chain for each block can be specified in combination with the --filters1=filters ... --filters9=filters options. These options define filter chains with an identifier between 1–9. Filter chain 0 can be used to refer to the default filter chain, which is the same as not specifying a filter chain. The filter chain identifier can be used before the un‐ compressed size, followed by a colon (:). For example, if one specifies --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB then blocks will be created using: • The filter chain specified by --filters1 and 2 MiB input • The filter chain specified by --filters3 and 2 MiB input • The filter chain specified by --filters2 and 4 MiB input • The filter chain specified by --filters2 and 4 MiB input • The default filter chain and 2 MiB input • The default filter chain and 4 MiB input for every block un‐ til end of input. If one specifies a size that exceeds the encoder's block size (either the default value in threaded mode or the value speci‐ fied with --block-size=size), the encoder will create additional blocks while keeping the boundaries specified in items. For ex‐ ample, if one specifies --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB and the input file is 80 MiB, one will get 11 blocks: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10, and 1 MiB. In multi-threaded mode the sizes of the blocks are stored in the block headers. This isn't done in single-threaded mode, so the encoded output won't be identical to that of the multi-threaded mode. --flush-timeout=timeout When compressing, if more than timeout milliseconds (a positive integer) has passed since the previous flush and reading more input would block, all the pending input data is flushed from the encoder and made available in the output stream. This can be useful if xz is used to compress data that is streamed over a network. Small timeout values make the data available at the receiving end with a small delay, but large timeout values give better compression ratio. This feature is disabled by default. If this option is speci‐ fied more than once, the last one takes effect. The special timeout value of 0 can be used to explicitly disable this fea‐ ture. This feature is not available on non-POSIX systems. This feature is still experimental. Currently xz is unsuitable for decompressing the stream in real time due to how xz does buffering. --memlimit-compress=limit Set a memory usage limit for compression. If this option is specified multiple times, the last one takes effect. If the compression settings exceed the limit, xz will attempt to adjust the settings downwards so that the limit is no longer ex‐ ceeded and display a notice that automatic adjustment was done. The adjustments are done in this order: reducing the number of threads, switching to single-threaded mode if even one thread in multi-threaded mode exceeds the limit, and finally reducing the LZMA2 dictionary size. When compressing with --format=raw or if --no-adjust has been specified, only the number of threads may be reduced since it can be done without affecting the compressed output. If the limit cannot be met even with the adjustments described above, an error is displayed and xz will exit with exit status 1. The limit can be specified in multiple ways: • The limit can be an absolute value in bytes. Using an inte‐ ger suffix like MiB can be useful. Example: --memlimit-com‐ press=80MiB • The limit can be specified as a percentage of total physical memory (RAM). This can be useful especially when setting the XZ_DEFAULTS environment variable in a shell initialization script that is shared between different computers. That way the limit is automatically bigger on systems with more mem‐ ory. Example: --memlimit-compress=70% • The limit can be reset back to its default value by setting it to 0. This is currently equivalent to setting the limit to max (no memory usage limit). For 32-bit xz there is a special case: if the limit would be over 4020 MiB, the limit is set to 4020 MiB. On MIPS32 2000 MiB is used instead. (The values 0 and max aren't affected by this. A similar feature doesn't exist for decompression.) This can be helpful when a 32-bit executable has access to 4 GiB address space (2 GiB on MIPS32) while hopefully doing no harm in other situations. See also the section Memory usage. --memlimit-decompress=limit Set a memory usage limit for decompression. This also affects the --list mode. If the operation is not possible without ex‐ ceeding the limit, xz will display an error and decompressing the file will fail. See --memlimit-compress=limit for possible ways to specify the limit. --memlimit-mt-decompress=limit Set a memory usage limit for multi-threaded decompression. This can only affect the number of threads; this will never make xz refuse to decompress a file. If limit is too low to allow any multi-threading, the limit is ignored and xz will continue in single-threaded mode. Note that if also --memlimit-decompress is used, it will always apply to both single-threaded and multi- threaded modes, and so the effective limit for multi-threading will never be higher than the limit set with --memlimit-decom‐ press. In contrast to the other memory usage limit options, --mem‐ limit-mt-decompress=limit has a system-specific default limit. xz --info-memory can be used to see the current value. This option and its default value exist because without any limit the threaded decompressor could end up allocating an in‐ sane amount of memory with some input files. If the default limit is too low on your system, feel free to increase the limit but never set it to a value larger than the amount of usable RAM as with appropriate input files xz will attempt to use that amount of memory even with a low number of threads. Running out of memory or swapping will not improve decompression perfor‐ mance. See --memlimit-compress=limit for possible ways to specify the limit. Setting limit to 0 resets the limit to the default sys‐ tem-specific value. -M limit, --memlimit=limit, --memory=limit This is equivalent to specifying --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Display an error and exit if the memory usage limit cannot be met without adjusting settings that affect the compressed out‐ put. That is, this prevents xz from switching the encoder from multi-threaded mode to single-threaded mode and from reducing the LZMA2 dictionary size. Even when this option is used the number of threads may be reduced to meet the memory usage limit as that won't affect the compressed output. Automatic adjusting is always disabled when creating raw streams (--format=raw). -T threads, --threads=threads Specify the number of worker threads to use. Setting threads to a special value 0 makes xz use up to as many threads as the pro‐ cessor(s) on the system support. The actual number of threads can be fewer than threads if the input file is not big enough for threading with the given settings or if using more threads would exceed the memory usage limit. The single-threaded and multi-threaded compressors produce dif‐ ferent output. Single-threaded compressor will give the small‐ est file size but only the output from the multi-threaded com‐ pressor can be decompressed using multiple threads. Setting threads to 1 will use the single-threaded mode. Setting threads to any other value, including 0, will use the multi-threaded compressor even if the system supports only one hardware thread. (xz 5.2.x used single-threaded mode in this situation.) To use multi-threaded mode with only one thread, set threads to +1. The + prefix has no effect with values other than 1. A memory usage limit can still make xz switch to single-threaded mode unless --no-adjust is used. Support for the + prefix was added in xz 5.4.0. If an automatic number of threads has been requested and no mem‐ ory usage limit has been specified, then a system-specific de‐ fault soft limit will be used to possibly limit the number of threads. It is a soft limit in sense that it is ignored if the number of threads becomes one, thus a soft limit will never stop xz from compressing or decompressing. This default soft limit will not make xz switch from multi-threaded mode to single- threaded mode. The active limits can be seen with xz --info-memory. Currently the only threading method is to split the input into blocks and compress them independently from each other. The de‐ fault block size depends on the compression level and can be overridden with the --block-size=size option. Threaded decompression only works on files that contain multiple blocks with size information in block headers. All large enough files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size has been used. The default value for threads is 0. In xz 5.4.x and older the default is 1. Custom compressor filter chains A custom filter chain allows specifying the compression settings in de‐ tail instead of relying on the settings associated to the presets. When a custom filter chain is specified, preset options (-0 ... -9 and --extreme) earlier on the command line are forgotten. If a preset op‐ tion is specified after one or more custom filter chain options, the new preset takes effect and the custom filter chain options specified earlier are forgotten. A filter chain is comparable to piping on the command line. When com‐ pressing, the uncompressed input goes to the first filter, whose output goes to the next filter (if any). The output of the last filter gets written to the compressed file. The maximum number of filters in the chain is four, but typically a filter chain has only one or two fil‐ ters. Many filters have limitations on where they can be in the filter chain: some filters can work only as the last filter in the chain, some only as a non-last filter, and some work in any position in the chain. De‐ pending on the filter, this limitation is either inherent to the filter design or exists to prevent security issues. A custom filter chain can be specified in two different ways. The op‐ tions --filters=filters and --filters1=filters ... --filters9=filters allow specifying an entire filter chain in one option using the liblzma filter string syntax. Alternatively, a filter chain can be specified by using one or more individual filter options in the order they are wanted in the filter chain. That is, the order of the individual fil‐ ter options is significant! When decoding raw streams (--format=raw), the filter chain must be specified in the same order as it was speci‐ fied when compressing. Any individual filter or preset options speci‐ fied before the full chain option (--filters=filters) will be forgot‐ ten. Individual filters specified after the full chain option will re‐ set the filter chain. Both the full and individual filter options take filter-specific op‐ tions as a comma-separated list. Extra commas in options are ignored. Every option has a default value, so specify those you want to change. To see the whole filter chain and options, use xz -vv (that is, use --verbose twice). This works also for viewing the filter chain options used by presets. --filters=filters Specify the full filter chain or a preset in a single option. Each filter can be separated by spaces or two dashes (--). fil‐ ters may need to be quoted on the shell command line so it is parsed as a single option. To denote options, use : or =. A preset can be prefixed with a - and followed with zero or more flags. The only supported flag is e to apply the same options as --extreme. --filters1=filters ... --filters9=filters Specify up to nine additional filter chains that can be used with --block-list. For example, when compressing an archive with executable files followed by text files, the executable part could use a filter chain with a BCJ filter and the text part only the LZMA2 filter. --filters-help Display a help message describing how to specify presets and custom filter chains in the --filters and --filters1=filters ... --filters9=filters options, and exit successfully. --lzma1[=options] --lzma2[=options] Add LZMA1 or LZMA2 filter to the filter chain. These filters can be used only as the last filter in the chain. LZMA1 is a legacy filter, which is supported almost solely due to the legacy .lzma file format, which supports only LZMA1. LZMA2 is an updated version of LZMA1 to fix some practical is‐ sues of LZMA1. The .xz format uses LZMA2 and doesn't support LZMA1 at all. Compression speed and ratios of LZMA1 and LZMA2 are practically the same. LZMA1 and LZMA2 share the same set of options: preset=preset Reset all LZMA1 or LZMA2 options to preset. Preset con‐ sist of an integer, which may be followed by single-let‐ ter preset modifiers. The integer can be from 0 to 9, matching the command line options -0 ... -9. The only supported modifier is currently e, which matches --ex‐ treme. If no preset is specified, the default values of LZMA1 or LZMA2 options are taken from the preset 6. dict=size Dictionary (history buffer) size indicates how many bytes of the recently processed uncompressed data is kept in memory. The algorithm tries to find repeating byte se‐ quences (matches) in the uncompressed data, and replace them with references to the data currently in the dictio‐ nary. The bigger the dictionary, the higher is the chance to find a match. Thus, increasing dictionary size usually improves compression ratio, but a dictionary big‐ ger than the uncompressed file is waste of memory. Typical dictionary size is from 64 KiB to 64 MiB. The minimum is 4 KiB. The maximum for compression is cur‐ rently 1.5 GiB (1536 MiB). The decompressor already sup‐ ports dictionaries up to one byte less than 4 GiB, which is the maximum for the LZMA1 and LZMA2 stream formats. Dictionary size and match finder (mf) together determine the memory usage of the LZMA1 or LZMA2 encoder. The same (or bigger) dictionary size is required for decompressing that was used when compressing, thus the memory usage of the decoder is determined by the dictionary size used when compressing. The .xz headers store the dictionary size either as 2^n or 2^n + 2^(n-1), so these sizes are somewhat preferred for compression. Other sizes will get rounded up when stored in the .xz headers. lc=lc Specify the number of literal context bits. The minimum is 0 and the maximum is 4; the default is 3. In addi‐ tion, the sum of lc and lp must not exceed 4. All bytes that cannot be encoded as matches are encoded as literals. That is, literals are simply 8-bit bytes that are encoded one at a time. The literal coding makes an assumption that the highest lc bits of the previous uncompressed byte correlate with the next byte. For example, in typical English text, an upper-case letter is often followed by a lower-case let‐ ter, and a lower-case letter is usually followed by an‐ other lower-case letter. In the US-ASCII character set, the highest three bits are 010 for upper-case letters and 011 for lower-case letters. When lc is at least 3, the literal coding can take advantage of this property in the uncompressed data. The default value (3) is usually good. If you want maxi‐ mum compression, test lc=4. Sometimes it helps a little, and sometimes it makes compression worse. If it makes it worse, test lc=2 too. lp=lp Specify the number of literal position bits. The minimum is 0 and the maximum is 4; the default is 0. Lp affects what kind of alignment in the uncompressed data is assumed when encoding literals. See pb below for more information about alignment. pb=pb Specify the number of position bits. The minimum is 0 and the maximum is 4; the default is 2. Pb affects what kind of alignment in the uncompressed data is assumed in general. The default means four-byte alignment (2^pb=2^2=4), which is often a good choice when there's no better guess. When the alignment is known, setting pb accordingly may reduce the file size a little. For example, with text files having one-byte alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can improve compression slightly. For UTF-16 text, pb=1 is a good choice. If the alignment is an odd number like 3 bytes, pb=0 might be the best choice. Even though the assumed alignment can be adjusted with pb and lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment. It might be worth taking into account when designing file formats that are likely to be often com‐ pressed with LZMA1 or LZMA2. mf=mf Match finder has a major effect on encoder speed, memory usage, and compression ratio. Usually Hash Chain match finders are faster than Binary Tree match finders. The default depends on the preset: 0 uses hc3, 1–3 use hc4, and the rest use bt4. The following match finders are supported. The memory usage formulas below are rough approximations, which are closest to the reality when dict is a power of two. hc3 Hash Chain with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 7.5 (if dict <= 16 MiB); dict * 5.5 + 64 MiB (if dict > 16 MiB) hc4 Hash Chain with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 7.5 (if dict <= 32 MiB); dict * 6.5 (if dict > 32 MiB) bt2 Binary Tree with 2-byte hashing Minimum value for nice: 2 Memory usage: dict * 9.5 bt3 Binary Tree with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 11.5 (if dict <= 16 MiB); dict * 9.5 + 64 MiB (if dict > 16 MiB) bt4 Binary Tree with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 11.5 (if dict <= 32 MiB); dict * 10.5 (if dict > 32 MiB) mode=mode Compression mode specifies the method to analyze the data produced by the match finder. Supported modes are fast and normal. The default is fast for presets 0–3 and nor‐ mal for presets 4–9. Usually fast is used with Hash Chain match finders and normal with Binary Tree match finders. This is also what the presets do. nice=nice Specify what is considered to be a nice length for a match. Once a match of at least nice bytes is found, the algorithm stops looking for possibly better matches. Nice can be 2–273 bytes. Higher values tend to give bet‐ ter compression ratio at the expense of speed. The de‐ fault depends on the preset. depth=depth Specify the maximum search depth in the match finder. The default is the special value of 0, which makes the compressor determine a reasonable depth from mf and nice. Reasonable depth for Hash Chains is 4–100 and 16–1000 for Binary Trees. Using very high values for depth can make the encoder extremely slow with some files. Avoid set‐ ting the depth over 1000 unless you are prepared to in‐ terrupt the compression in case it is taking far too long. When decoding raw streams (--format=raw), LZMA2 needs only the dictionary size. LZMA1 needs also lc, lp, and pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Add a branch/call/jump (BCJ) filter to the filter chain. These filters can be used only as a non-last filter in the filter chain. A BCJ filter converts relative addresses in the machine code to their absolute counterparts. This doesn't change the size of the data but it increases redundancy, which can help LZMA2 to produce 0–15 % smaller .xz file. The BCJ filters are always re‐ versible, so using a BCJ filter for wrong type of data doesn't cause any data loss, although it may make the compression ratio slightly worse. The BCJ filters are very fast and use an in‐ significant amount of memory. These BCJ filters have known problems related to the compression ratio: • Some types of files containing executable code (for example, object files, static libraries, and Linux kernel modules) have the addresses in the instructions filled with filler values. These BCJ filters will still do the address conver‐ sion, which will make the compression worse with these files. • If a BCJ filter is applied on an archive, it is possible that it makes the compression ratio worse than not using a BCJ filter. For example, if there are similar or even identical executables then filtering will likely make the files less similar and thus compression is worse. The contents of non- executable files in the same archive can matter too. In practice one has to try with and without a BCJ filter to see which is better in each situation. Different instruction sets have different alignment: the exe‐ cutable file must be aligned to a multiple of this value in the input data to make the filter work. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit or 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Since the BCJ-filtered data is usually compressed with LZMA2, the compression ratio may be improved slightly if the LZMA2 op‐ tions are set to match the alignment of the selected BCJ filter. Examples: • IA-64 filter has 16-byte alignment so pb=4,lp=4,lc=0 is good with LZMA2 (2^4=16). • RISC-V code has 2-byte or 4-byte alignment depending on whether the file contains 16-bit compressed instructions (the C extension). When 16-bit instructions are used, pb=2,lp=1,lc=3 or pb=1,lp=1,lc=3 is good. When 16-bit in‐ structions aren't present, pb=2,lp=2,lc=2 is the best. read‐ elf -h can be used to check if "RVC" appears on the "Flags" line. • ARM64 is always 4-byte aligned so pb=2,lp=2,lc=2 is the best. • The x86 filter is an exception. It's usually good to stick to LZMA2's defaults (pb=2,lp=0,lc=3) when compressing x86 ex‐ ecutables. All BCJ filters support the same options: start=offset Specify the start offset that is used when converting be‐ tween relative and absolute addresses. The offset must be a multiple of the alignment of the filter (see the ta‐ ble above). The default is zero. In practice, the de‐ fault is good; specifying a custom offset is almost never useful. --delta[=options] Add the Delta filter to the filter chain. The Delta filter can be only used as a non-last filter in the filter chain. Currently only simple byte-wise delta calculation is supported. It can be useful when compressing, for example, uncompressed bitmap images or uncompressed PCM audio. However, special pur‐ pose algorithms may give significantly better results than Delta + LZMA2. This is true especially with audio, which compresses faster and better, for example, with flac(1). Supported options: dist=distance Specify the distance of the delta calculation in bytes. distance must be 1–256. The default is 1. For example, with dist=2 and eight-byte input A1 B1 A2 B3 A3 B5 A4 B7, the output will be A1 B1 01 02 01 02 01 02. Other options -q, --quiet Suppress warnings and notices. Specify this twice to suppress errors too. This option has no effect on the exit status. That is, even if a warning was suppressed, the exit status to indi‐ cate a warning is still used. -v, --verbose Be verbose. If standard error is connected to a terminal, xz will display a progress indicator. Specifying --verbose twice will give even more verbose output. The progress indicator shows the following information: • Completion percentage is shown if the size of the input file is known. That is, the percentage cannot be shown in pipes. • Amount of compressed data produced (compressing) or consumed (decompressing). • Amount of uncompressed data consumed (compressing) or pro‐ duced (decompressing). • Compression ratio, which is calculated by dividing the amount of compressed data processed so far by the amount of uncom‐ pressed data processed so far. • Compression or decompression speed. This is measured as the amount of uncompressed data consumed (compression) or pro‐ duced (decompression) per second. It is shown after a few seconds have passed since xz started processing the file. • Elapsed time in the format M:SS or H:MM:SS. • Estimated remaining time is shown only when the size of the input file is known and a couple of seconds have already passed since xz started processing the file. The time is shown in a less precise format which never has any colons, for example, 2 min 30 s. When standard error is not a terminal, --verbose will make xz print the filename, compressed size, uncompressed size, compres‐ sion ratio, and possibly also the speed and elapsed time on a single line to standard error after compressing or decompressing the file. The speed and elapsed time are included only when the operation took at least a few seconds. If the operation didn't finish, for example, due to user interruption, also the comple‐ tion percentage is printed if the size of the input file is known. -Q, --no-warn Don't set the exit status to 2 even if a condition worth a warn‐ ing was detected. This option doesn't affect the verbosity level, thus both --quiet and --no-warn have to be used to not display warnings and to not alter the exit status. --robot Print messages in a machine-parsable format. This is intended to ease writing frontends that want to use xz instead of li‐ blzma, which may be the case with various scripts. The output with this option enabled is meant to be stable across xz re‐ leases. See the section ROBOT MODE for details. --info-memory Display, in human-readable format, how much physical memory (RAM) and how many processor threads xz thinks the system has and the memory usage limits for compression and decompression, and exit successfully. -h, --help Display a help message describing the most commonly used op‐ tions, and exit successfully. -H, --long-help Display a help message describing all features of xz, and exit successfully -V, --version Display the version number of xz and liblzma in human readable format. To get machine-parsable output, specify --robot before --version. ROBOT MODE The robot mode is activated with the --robot option. It makes the out‐ put of xz easier to parse by other programs. Currently --robot is sup‐ ported only together with --list, --filters-help, --info-memory, and --version. It will be supported for compression and decompression in the future. List mode xz --robot --list uses tab-separated output. The first column of every line has a string that indicates the type of the information found on that line: name This is always the first line when starting to list a file. The second column on the line is the filename. file This line contains overall information about the .xz file. This line is always printed after the name line. stream This line type is used only when --verbose was specified. There are as many stream lines as there are streams in the .xz file. block This line type is used only when --verbose was specified. There are as many block lines as there are blocks in the .xz file. The block lines are shown after all the stream lines; different line types are not interleaved. summary This line type is used only when --verbose was specified twice. This line is printed after all block lines. Like the file line, the summary line contains overall information about the .xz file. totals This line is always the very last line of the list output. It shows the total counts and sizes. The columns of the file lines: 2. Number of streams in the file 3. Total number of blocks in the stream(s) 4. Compressed size of the file 5. Uncompressed size of the file 6. Compression ratio, for example, 0.123. If ratio is over 9.999, three dashes (---) are displayed instead of the ra‐ tio. 7. Comma-separated list of integrity check names. The follow‐ ing strings are used for the known check types: None, CRC32, CRC64, and SHA-256. For unknown check types, Unknown-N is used, where N is the Check ID as a decimal number (one or two digits). 8. Total size of stream padding in the file The columns of the stream lines: 2. Stream number (the first stream is 1) 3. Number of blocks in the stream 4. Compressed start offset 5. Uncompressed start offset 6. Compressed size (does not include stream padding) 7. Uncompressed size 8. Compression ratio 9. Name of the integrity check 10. Size of stream padding The columns of the block lines: 2. Number of the stream containing this block 3. Block number relative to the beginning of the stream (the first block is 1) 4. Block number relative to the beginning of the file 5. Compressed start offset relative to the beginning of the file 6. Uncompressed start offset relative to the beginning of the file 7. Total compressed size of the block (includes headers) 8. Uncompressed size 9. Compression ratio 10. Name of the integrity check If --verbose was specified twice, additional columns are included on the block lines. These are not displayed with a single --verbose, be‐ cause getting this information requires many seeks and can thus be slow: 11. Value of the integrity check in hexadecimal 12. Block header size 13. Block flags: c indicates that compressed size is present, and u indicates that uncompressed size is present. If the flag is not set, a dash (-) is shown instead to keep the string length fixed. New flags may be added to the end of the string in the future. 14. Size of the actual compressed data in the block (this ex‐ cludes the block header, block padding, and check fields) 15. Amount of memory (in bytes) required to decompress this block with this xz version 16. Filter chain. Note that most of the options used at com‐ pression time cannot be known, because only the options that are needed for decompression are stored in the .xz headers. The columns of the summary lines: 2. Amount of memory (in bytes) required to decompress this file with this xz version 3. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 4. Minimum xz version required to decompress the file The columns of the totals line: 2. Number of streams 3. Number of blocks 4. Compressed size 5. Uncompressed size 6. Average compression ratio 7. Comma-separated list of integrity check names that were present in the files 8. Stream padding size 9. Number of files. This is here to keep the order of the ear‐ lier columns the same as on file lines. If --verbose was specified twice, additional columns are included on the totals line: 10. Maximum amount of memory (in bytes) required to decompress the files with this xz version 11. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 12. Minimum xz version required to decompress the file Future versions may add new line types and new columns can be added to the existing line types, but the existing columns won't be changed. Filters help xz --robot --filters-help prints the supported filters in the following format: filter:option=<value>,option=<value>... filter Name of the filter option Name of a filter specific option value Numeric value ranges appear as <min-max>. String value choices are shown within < > and separated by a | character. Each filter is printed on its own line. Memory limit information xz --robot --info-memory prints a single line with multiple tab-sepa‐ rated columns: 1. Total amount of physical memory (RAM) in bytes. 2. Memory usage limit for compression in bytes (--memlimit-compress). A special value of 0 indicates the default setting which for sin‐ gle-threaded mode is the same as no limit. 3. Memory usage limit for decompression in bytes (--memlimit-decom‐ press). A special value of 0 indicates the default setting which for single-threaded mode is the same as no limit. 4. Since xz 5.3.4alpha: Memory usage for multi-threaded decompression in bytes (--memlimit-mt-decompress). This is never zero because a system-specific default value shown in the column 5 is used if no limit has been specified explicitly. This is also never greater than the value in the column 3 even if a larger value has been specified with --memlimit-mt-decompress. 5. Since xz 5.3.4alpha: A system-specific default memory usage limit that is used to limit the number of threads when compressing with an automatic number of threads (--threads=0) and no memory usage limit has been specified (--memlimit-compress). This is also used as the default value for --memlimit-mt-decompress. 6. Since xz 5.3.4alpha: Number of available processor threads. In the future, the output of xz --robot --info-memory may have more columns, but never more than a single line. Version xz --robot --version prints the version number of xz and liblzma in the following format: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Major version. YYY Minor version. Even numbers are stable. Odd numbers are alpha or beta versions. ZZZ Patch level for stable releases or just a counter for develop‐ ment releases. S Stability. 0 is alpha, 1 is beta, and 2 is stable. S should be always 2 when YYY is even. XYYYZZZS are the same on both lines if xz and liblzma are from the same XZ Utils release. Examples: 4.999.9beta is 49990091 and 5.0.0 is 50000002. EXIT STATUS 0 All is good. 1 An error occurred. 2 Something worth a warning occurred, but no actual errors oc‐ curred. Notices (not warnings or errors) printed on standard error don't affect the exit status. ENVIRONMENT xz parses space-separated lists of options from the environment vari‐ ables XZ_DEFAULTS and XZ_OPT, in this order, before parsing the options from the command line. Note that only options are parsed from the en‐ vironment variables; all non-options are silently ignored. Parsing is done with getopt_long(3) which is used also for the command line argu‐ ments. XZ_DEFAULTS User-specific or system-wide default options. Typically this is set in a shell initialization script to enable xz's memory usage limiter by default. Excluding shell initialization scripts and similar special cases, scripts must never set or unset XZ_DE‐ FAULTS. XZ_OPT This is for passing options to xz when it is not possible to set the options directly on the xz command line. This is the case when xz is run by a script or tool, for example, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Scripts may use XZ_OPT, for example, to set script-specific de‐ fault compression options. It is still recommended to allow users to override XZ_OPT if that is reasonable. For example, in sh(1) scripts one may use something like this: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY The command line syntax of xz is practically a superset of lzma, un‐ lzma, and lzcat as found from LZMA Utils 4.32.x. In most cases, it is possible to replace LZMA Utils with XZ Utils without breaking existing scripts. There are some incompatibilities though, which may sometimes cause problems. Compression preset levels The numbering of the compression level presets is not identical in xz and LZMA Utils. The most important difference is how dictionary sizes are mapped to different presets. Dictionary size is roughly equal to the decompressor memory usage. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB The dictionary size differences affect the compressor memory usage too, but there are some other differences between LZMA Utils and XZ Utils, which make the difference even bigger: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB The default preset level in LZMA Utils is -7 while in XZ Utils it is -6, so both use an 8 MiB dictionary by default. Streamed vs. non-streamed .lzma files The uncompressed size of the file can be stored in the .lzma header. LZMA Utils does that when compressing regular files. The alternative is to mark that uncompressed size is unknown and use end-of-payload marker to indicate where the decompressor should stop. LZMA Utils uses this method when uncompressed size isn't known, which is the case, for example, in pipes. xz supports decompressing .lzma files with or without end-of-payload marker, but all .lzma files created by xz will use end-of-payload marker and have uncompressed size marked as unknown in the .lzma header. This may be a problem in some uncommon situations. For exam‐ ple, a .lzma decompressor in an embedded device might work only with files that have known uncompressed size. If you hit this problem, you need to use LZMA Utils or LZMA SDK to create .lzma files with known un‐ compressed size. Unsupported .lzma files The .lzma format allows lc values up to 8, and lp values up to 4. LZMA Utils can decompress files with any lc and lp, but always creates files with lc=3 and lp=0. Creating files with other lc and lp is possible with xz and with LZMA SDK. The implementation of the LZMA1 filter in liblzma requires that the sum of lc and lp must not exceed 4. Thus, .lzma files, which exceed this limitation, cannot be decompressed with xz. LZMA Utils creates only .lzma files which have a dictionary size of 2^n (a power of 2) but accepts files with any dictionary size. liblzma ac‐ cepts only .lzma files which have a dictionary size of 2^n or 2^n + 2^(n-1). This is to decrease false positives when detecting .lzma files. These limitations shouldn't be a problem in practice, since practically all .lzma files have been compressed with settings that liblzma will accept. Trailing garbage When decompressing, LZMA Utils silently ignore everything after the first .lzma stream. In most situations, this is a bug. This also means that LZMA Utils don't support decompressing concatenated .lzma files. If there is data left after the first .lzma stream, xz considers the file to be corrupt unless --single-stream was used. This may break ob‐ scure scripts which have assumed that trailing garbage is ignored. NOTES Compressed output may vary The exact compressed output produced from the same uncompressed input file may vary between XZ Utils versions even if compression options are identical. This is because the encoder can be improved (faster or bet‐ ter compression) without affecting the file format. The output can vary even between different builds of the same XZ Utils version, if different build options are used. The above means that once --rsyncable has been implemented, the result‐ ing files won't necessarily be rsyncable unless both old and new files have been compressed with the same xz version. This problem can be fixed if a part of the encoder implementation is frozen to keep rsynca‐ ble output stable across xz versions. Embedded .xz decompressors Embedded .xz decompressor implementations like XZ Embedded don't neces‐ sarily support files created with integrity check types other than none and crc32. Since the default is --check=crc64, you must use --check=none or --check=crc32 when creating files for embedded systems. Outside embedded systems, all .xz format decompressors support all the check types, or at least are able to decompress the file without veri‐ fying the integrity check if the particular check is not supported. XZ Embedded supports BCJ filters, but only with the default start off‐ set. EXAMPLES Basics Compress the file foo into foo.xz using the default compression level (-6), and remove foo if compression is successful: xz foo Decompress bar.xz into bar and don't remove bar.xz even if decompres‐ sion is successful: xz -dk bar.xz Create baz.tar.xz with the preset -4e (-4 --extreme), which is slower than the default -6, but needs less memory for compression and decom‐ pression (48 MiB and 5 MiB, respectively): tar cf - baz | xz -4e > baz.tar.xz A mix of compressed and uncompressed files can be decompressed to stan‐ dard output with a single command: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Parallel compression of many files On GNU and *BSD, find(1) and xargs(1) can be used to parallelize com‐ pression of many files: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 The -P option to xargs(1) sets the number of parallel xz processes. The best value for the -n option depends on how many files there are to be compressed. If there are only a couple of files, the value should probably be 1; with tens of thousands of files, 100 or even more may be appropriate to reduce the number of xz processes that xargs(1) will eventually create. The option -T1 for xz is there to force it to single-threaded mode, be‐ cause xargs(1) is used to control the amount of parallelization. Robot mode Calculate how many bytes have been saved in total after compressing multiple files: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' A script may want to know that it is using new enough xz. The follow‐ ing sh(1) script checks that the version number of the xz tool is at least 5.0.0. This method is compatible with old beta versions, which didn't support the --robot option: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Set a memory usage limit for decompression using XZ_OPT, but if a limit has already been set, don't increase it: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Custom compressor filter chains The simplest use for custom filter chains is customizing a LZMA2 pre‐ set. This can be useful, because the presets cover only a subset of the potentially useful combinations of compression settings. The CompCPU columns of the tables from the descriptions of the options -0 ... -9 and --extreme are useful when customizing LZMA2 presets. Here are the relevant parts collected from those two tables: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 If you know that a file requires somewhat big dictionary (for example, 32 MiB) to compress well, but you want to compress it quicker than xz -8 would do, a preset with a low CompCPU value (for example, 1) can be modified to use a bigger dictionary: xz --lzma2=preset=1,dict=32MiB foo.tar With certain files, the above command may be faster than xz -6 while compressing significantly better. However, it must be emphasized that only some files benefit from a big dictionary while keeping the CompCPU value low. The most obvious situation, where a big dictionary can help a lot, is an archive containing very similar files of at least a few megabytes each. The dictionary size has to be significantly bigger than any individual file to allow LZMA2 to take full advantage of the similarities between consecutive files. If very high compressor and decompressor memory usage is fine, and the file being compressed is at least several hundred megabytes, it may be useful to use an even bigger dictionary than the 64 MiB that xz -9 would use: xz -vv --lzma2=dict=192MiB big_foo.tar Using -vv (--verbose --verbose) like in the above example can be useful to see the memory requirements of the compressor and decompressor. Re‐ member that using a dictionary bigger than the size of the uncompressed file is waste of memory, so the above command isn't useful for small files. Sometimes the compression time doesn't matter, but the decompressor memory usage has to be kept low, for example, to make it possible to decompress the file on an embedded system. The following command uses -6e (-6 --extreme) as a base and sets the dictionary to only 64 KiB. The resulting file can be decompressed with XZ Embedded (that's why there is --check=crc32) using about 100 KiB of memory. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo If you want to squeeze out as many bytes as possible, adjusting the number of literal context bits (lc) and number of position bits (pb) can sometimes help. Adjusting the number of literal position bits (lp) might help too, but usually lc and pb are more important. For example, a source code archive contains mostly US-ASCII text, so something like the following might give slightly (like 0.1 %) smaller file than xz -6e (try also without lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Using another filter together with LZMA2 can improve compression with certain file types. For example, to compress a x86-32 or x86-64 shared library using the x86 BCJ filter: xz --x86 --lzma2 libfoo.so Note that the order of the filter options is significant. If --x86 is specified after --lzma2, xz will give an error, because there cannot be any filter after LZMA2, and also because the x86 BCJ filter cannot be used as the last filter in the chain. The Delta filter together with LZMA2 can give good results with bitmap images. It should usually beat PNG, which has a few more advanced fil‐ ters than simple delta but uses Deflate for the actual compression. The image has to be saved in uncompressed format, for example, as un‐ compressed TIFF. The distance parameter of the Delta filter is set to match the number of bytes per pixel in the image. For example, 24-bit RGB bitmap needs dist=3, and it is also good to pass pb=0 to LZMA2 to accommodate the three-byte alignment: xz --delta=dist=3 --lzma2=pb=0 foo.tiff If multiple images have been put into a single archive (for example, .tar), the Delta filter will work on that too as long as all images have the same number of bytes per pixel. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html> Tukaani 2024-12-30 XZ(1)
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Сжатие или распаковка файлов .xz и .lzma SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz эквивалентно xz --decompress. xzcat эквивалентно xz --decompress --stdout. lzma эквивалентно xz --format=lzma. unlzma эквивалентно xz --format=lzma --decompress. lzcat эквивалентно xz --format=lzma --decompress --stdout. При написании скриптов, которые требуют распаковки файлов, рекомендуется всегда использовать имя xz с подходящими аргументами (xz -d или xz -dc) вместо имён unxz и xzcat. DESCRIPTION xz - это универсальный инструмент сжатия данных с синтаксисом командной строки, похожим на gzip(1) и bzip2(1). Родной формат файлов - это формат .xz, но также поддерживается устаревший формат .lzma, используемый LZMA Utils, и сырые сжатые потоки без заголовков контейнера. Кроме того, поддерживается распаковка формата .lz, используемого lzip. xz сжимает или распаковывает каждый файл в соответствии с выбранным режимом операции. Если файлы не указаны или файл указан как -, xz читает из стандартного ввода и записывает обработанные данные в стандартный вывод. xz отказывается (выводит ошибку и пропускает файл) записывать сжатые данные в стандартный вывод, если это терминал. Аналогично, xz отказывается читать сжатые данные из стандартного ввода, если это терминал. Если не указан --stdout, файлы, отличные от -, записываются в новый файл, имя которого получается из имени исходного файла: • При сжатии, суффикс целевого формата файла (.xz или .lzma) добавляется к имени исходного файла для получения имени целевого файла. • При распаковке, суффикс .xz, .lzma или .lz удаляется из имени файла для получения имени целевого файла. xz также распознаёт суффиксы .txz и .tlz и заменяет их на суффикс .tar. Если целевой файл уже существует, выводится ошибка и файл пропускается. Если не записывается в стандартный вывод, xz выведет предупреждение и пропустит файл, если выполняется любое из следующих условий: • Файл не является обычным файлом. Символические ссылки не следуются и, следовательно, не считаются обычными файлами. • Файл имеет более одной жёсткой ссылки. • Файл имеет установленные биты setuid, setgid или sticky. • Режим операции установлен на сжатие, и файл уже имеет суффикс целевого формата файла (.xz или .txz при сжатии в формат .xz, и .lzma или .tlz при сжатии в формат .lzma). • Режим операции установлен на распаковку, и файл не имеет суффикса ни одного из поддерживаемых форматов файлов (.xz, .txz, .lzma, .tlz или .lz). После успешного сжатия или распаковки файла xz копирует владельца, группу, права доступа, время доступа и время изменения из исходного файла в целевой файл. Если копирование группы не удаётся, права доступа изменяются так, чтобы целевой файл не стал доступным для пользователей, у которых не было доступа к исходному файлу. xz пока не поддерживает копирование другой метаданных, таких как списки контроля доступа или расширенные атрибуты. После успешного закрытия целевого файла исходный файл удаляется, если не указан --keep. Исходный файл никогда не удаляется, если вывод записывается в стандартный вывод или если возникает ошибка. Отправка сигнала SIGINFO или SIGUSR1 процессу xz заставляет его вывести информацию о прогрессе в стандартный вывод ошибок. Это имеет ограниченное применение, поскольку, если стандартный вывод ошибок - это терминал, использование --verbose отобразит автоматически обновляемый индикатор прогресса. Использование памяти Использование памяти xz варьируется от нескольких сотен килобайтов до нескольких гигабайт в зависимости от настроек сжатия. Настройки, используемые при сжатии файла, определяют требования к памяти декомпрессора. Обычно декомпрессору требуется 5%–20% от количества памяти, которое потребовалось компрессору при создании файла. Например, распаковка файла, созданного с помощью xz -9, в настоящее время требует 65 MiB памяти. Тем не менее, возможно наличие файлов .xz, которые требуют нескольких гигабайт памяти для распаковки. Особенно пользователи старых систем могут найти возможность очень большого использования памяти раздражающей. Чтобы предотвратить неприятные сюрпризы, xz имеет встроенный лимитер использования памяти, который по умолчанию отключён. Хотя некоторые операционные системы предоставляют способы ограничения использования памяти процессами, полагаться на это не сочли достаточно гибким (например, использование ulimit(1) для ограничения виртуальной памяти склонно нарушать mmap(2)). Лимитер использования памяти можно включить с помощью опции командной строки --memlimit=limit. Часто удобнее включить лимитер по умолчанию, установив переменную окружения XZ_DEFAULTS, например, XZ_DEFAULTS=--memlimit=150MiB. Возможна установка лимитов отдельно для сжатия и распаковки с помощью --memlimit-compress=limit и --memlimit-decompress=limit. Использование этих двух опций вне XZ_DEFAULTS редко полезно, потому что один запуск xz не может выполнять одновременно сжатие и распаковку, и --memlimit=limit (или -M limit) короче для ввода в командной строке. Если указанный лимит использования памяти превышен при распаковке, xz выведет ошибку, и распаковка файла не удастся. Если лимит превышен при сжатии, xz попытается уменьшить настройки так, чтобы лимит больше не превышался (кроме случаев использования --format=raw или --no-adjust). Таким образом, операция не завершится неудачей, если лимит не очень мал. Масштабирование настроек выполняется в шагах, которые не соответствуют пресетам уровней сжатия, например, если лимит всего на немного меньше, чем требуется для xz -9, настройки будут уменьшены всего на немного, а не полностью до xz -8. Конкатенация и заполнение файлов .xz Возможна конкатенация файлов .xz как есть. xz будет распаковывать такие файлы, как будто это один файл .xz. Возможна вставка заполнения между конкатенированными частями или после последней части. Заполнение должно состоять из нулевых байтов, и размер заполнения должен быть кратным четырём байтам. Это может быть полезно, например, если файл .xz хранится на носителе, который измеряет размеры файлов в блоках по 512 байт. Конкатенация и заполнение не допускаются для файлов .lzma или сырых потоков. OPTIONS Суффиксы целых чисел и специальные значения В большинстве мест, где ожидается целочисленный аргумент, поддерживается необязательный суффикс для удобного указания больших целых чисел. Между целым числом и суффиксом не должно быть пробелов. KiB Умножить целое число на 1 024 (2^10). Ki, k, kB, K и KB принимаются как синонимы для KiB. MiB Умножить целое число на 1 048 576 (2^20). Mi, m, M и MB принимаются как синонимы для MiB. GiB Умножить целое число на 1 073 741 824 (2^30). Gi, g, G и GB принимаются как синонимы для GiB. Специальное значение max может использоваться для указания максимального целочисленного значения, поддерживаемого опцией. Режим операции Если несколько опций режима операции указаны, последняя вступает в силу. -z, --compress Сжатие. Это режим операции по умолчанию, если ни одна опция режима операции не указана и другой режим операции не подразумевается из имени команды (например, unxz подразумевает --decompress). После успешного сжатия исходный файл удаляется, если не записывается в стандартный вывод или не указан --keep. -d, --decompress, --uncompress Распаковка. После успешной распаковки исходный файл удаляется, если не записывается в стандартный вывод или не указан --keep. -t, --test Проверить целостность сжатых файлов. Эта опция эквивалентна --decompress --stdout, за исключением того, что распакованные данные отбрасываются вместо записи в стандартный вывод. Файлы не создаются и не удаляются. -l, --list Вывести информацию о сжатых файлах. Не производится распакованный вывод, и файлы не создаются или не удаляются. В режиме списка программа не может читать сжатые данные из стандартного ввода или из других неподвижных источников. По умолчанию список показывает базовую информацию о файлах, один файл на строку. Для получения более детальной информации используйте также опцию --verbose. Для ещё большего количества информации используйте --verbose дважды, но учтите, что это может быть медленно, поскольку получение всей дополнительной информации требует многих поисков. Ширина подробного вывода превышает 80 символов, так что перенаправление вывода, например, в less -S, может быть удобным, если терминал недостаточно широкий. Точный вывод может варьироваться между версиями xz и разными локалями. Для машинно-читаемого вывода используйте --robot --list. Модификаторы операции -k, --keep Не удалять входные файлы. С версии xz 5.2.6 эта опция также заставляет xz сжимать или распаковывать, даже если вход - это символическая ссылка на обычный файл, имеет более одной жёсткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. В более ранних версиях это делалось только с --force. -f, --force Эта опция имеет несколько эффектов: • Если целевой файл уже существует, удалить его перед сжатием или распаковкой. • Сжимать или распаковывать, даже если вход - это символическая ссылка на обычный файл, имеет более одной жёсткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. • При использовании с --decompress --stdout, если xz не может распознать тип исходного файла, скопировать исходный файл как есть в стандартный вывод. Это позволяет использовать xzcat --force как cat(1) для файлов, которые не были сжаты с xz. Обратите внимание, что в будущем xz может поддерживать новые форматы сжатых файлов, что может заставить xz распаковывать больше типов файлов вместо копирования их как есть в стандартный вывод. --format=format можно использовать для ограничения xz распаковкой только одного формата файла. -c, --stdout, --to-stdout Записывать сжатые или распакованные данные в стандартный вывод вместо файла. Это подразумевает --keep. --single-stream Распаковывать только первый поток .xz и молча игнорировать возможные оставшиеся входные данные после потока. Нормально такие завершающие мусорные данные заставляют xz вывести ошибку. xz никогда не распаковывает более одного потока из файлов .lzma или сырых потоков, но эта опция всё равно заставляет xz игнорировать возможные завершающие данные после файла .lzma или сырого потока. Эта опция не имеет эффекта, если режим операции не --decompress или --test. --no-sparse Отключить создание разреженных файлов. По умолчанию, если распаковывается в обычный файл, xz пытается сделать файл разреженным, если распакованные данные содержат длинные последовательности бинарных нулей. Это также работает при записи в стандартный вывод, если стандартный вывод подключён к обычному файлу и выполняются определённые дополнительные условия для безопасности. Создание разреженных файлов может сэкономить место на диске и ускорить распаковку за счёт уменьшения количества операций ввода/вывода. -S .suf, --suffix=.suf При сжатии, использовать .suf в качестве суффикса для целевого файла вместо .xz или .lzma. Если не записывается в стандартный вывод и исходный файл уже имеет суффикс .suf, выводится предупреждение и файл пропускается. При распаковке, распознавать файлы с суффиксом .suf в дополнение к файлам с суффиксами .xz, .txz, .lzma, .tlz или .lz. Если исходный файл имеет суффикс .suf, суффикс удаляется для получения имени целевого файла. При сжатии или распаковке сырых потоков (--format=raw), суффикс всегда должен быть указан, если не записывается в стандартный вывод, поскольку для сырых потоков нет суффикса по умолчанию. --files[=file] Читать имена файлов для обработки из file; если file опущено, имена файлов читаются из стандартного ввода. Имена файлов должны заканчиваться символом новой строки. Тирка (-) считается обычным именем файла; это не означает стандартный ввод. Если имена файлов также указаны как аргументы командной строки, они обрабатываются перед именами файлов, прочитанными из file. --files0[=file] Это идентично --files[=file], за исключением того, что каждое имя файла должно заканчиваться нулевым символом. Основные опции формата файлов и сжатия -F format, --format=format Указать формат файла для сжатия или распаковки: auto Это значение по умолчанию. При сжатии auto эквивалентно xz. При распаковке формат входного файла определяется автоматически. Обратите внимание, что сырые потоки (созданные с --format=raw) не могут быть автоматически определены. xz Сжимать в формат файла .xz или принимать только файлы .xz при распаковке. lzma, alone Сжимать в устаревший формат файла .lzma или принимать только файлы .lzma при распаковке. Альтернативное имя alone предоставлено для обратной совместимости с LZMA Utils. lzip При распаковке принимать только файлы .lz. Сжатие не поддерживается. Поддерживаются версия формата 0 и нерасширенная версия 1. Файлы версии 0 создавались lzip 1.3 и старше. Такие файлы не распространены, но могут быть найдены в архивах файлов, поскольку несколько исходных пакетов были выпущены в этом формате. Пользователи могут иметь старые личные файлы в этом формате. Поддержка распаковки версии формата 0 была удалена в lzip 1.18. lzip 1.4 и новее создают файлы в формате версии 1. Расширение синхронизированного сброса для версии формата 1 было добавлено в lzip 1.6. Это расширение редко используется и не поддерживается xz (диагностируется как повреждённый ввод). raw Сжимать или распаковывать сырой поток (без заголовков). Это предназначено только для продвинутых пользователей. Чтобы декодировать сырые потоки, вам нужно использовать --format=raw и явно указать цепочку фильтров, которая обычно хранилась бы в заголовках контейнера. -C check, --check=check Указать тип проверки целостности. Проверка вычисляется из несжатых данных и хранится в файле .xz. Эта опция имеет эффект только при сжатии в формат .xz; формат .lzma не поддерживает проверки целостности. Проверка целостности (если она есть) проверяется при распаковке файла .xz. Поддерживаемые типы проверок: none Не вычислять проверку целостности вообще. Это обычно плохая идея. Это может быть полезно, когда целостность данных проверяется другими средствами. crc32 Вычислить CRC32 с использованием полинома из IEEE-802.3 (Ethernet). crc64 Вычислить CRC64 с использованием полинома из ECMA-182. Это значение по умолчанию, поскольку оно немного лучше, чем CRC32, для обнаружения повреждённых файлов, а разница в скорости незначительна. sha256 Вычислить SHA-256. Это немного медленнее, чем CRC32 и CRC64. Целостность заголовков .xz всегда проверяется с CRC32. Это невозможно изменить или отключить. --ignore-check Не проверять проверку целостности сжатых данных при распаковке. Значения CRC32 в заголовках .xz всё равно будут проверены нормально. Не используйте эту опцию, если вы не знаете, что делаете. Возможные причины использования этой опции: • Попытка восстановить данные из повреждённого файла .xz. • Увеличение скорости распаковки. Это имеет значение в основном с SHA-256 или с файлами, которые сжаты очень хорошо. Рекомендуется не использовать эту опцию для этой цели, если целостность файла не проверяется внешне другим способом. -0 ... -9 Выбрать пресет уровня сжатия. По умолчанию -6. Если указано несколько пресетов, последний вступает в силу. Если уже указана пользовательская цепочка фильтров, установка пресета уровня сжатия сбрасывает пользовательскую цепочку фильтров. Различия между пресетами более значительны, чем в gzip(1) и bzip2(1). Выбранные настройки сжатия определяют требования к памяти декомпрессора, поэтому использование слишком высокого пресета может сделать болезненным распаковку файла на старой системе с небольшим количеством ОЗУ. В частности, не стоит слепо использовать -9 для всего, как это часто бывает с gzip(1) и bzip2(1). -0 ... -3 Это относительно быстрые пресеты. -0 иногда быстрее, чем gzip -9, при значительно лучшем сжатии. Более высокие из них часто имеют скорость, сравнимую с bzip2(1) при сопоставимом или лучшем коэффициенте сжатия, хотя результаты сильно зависят от типа сжимаемых данных. -4 ... -6 Хорошее до очень хорошего сжатия при разумном использовании памяти декомпрессора, даже для старых систем. -6 - это значение по умолчанию, которое обычно подходит для распространения файлов, которые должны быть распакованы даже на системах с всего 16 MiB ОЗУ. (-5e или -6e также стоит рассмотреть. См. --extreme.) -7 ... -9 Это как -6, но с более высокими требованиями к памяти компрессора и декомпрессора. Эти пресеты полезны только при сжатии файлов больше 8 MiB, 16 MiB и 32 MiB соответственно. На том же оборудовании скорость распаковки примерно постоянна по количеству байт сжатых данных в секунду. Другими словами, чем лучше сжатие, тем быстрее обычно будет распаковка. Это также означает, что количество несжатого вывода, произведённого в секунду, может сильно варьироваться. В следующей таблице суммируются особенности пресетов: tab(;); c c c c c n n n n n. Preset;DictSize;CompCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Описания столбцов: • DictSize - размер словаря LZMA2. Это трата памяти использовать словарь больше, чем размер несжатого файла. Поэтому лучше избегать пресетов -7 ... -9, когда в них нет реальной нужды. При -6 и ниже, количество потраченной памяти обычно достаточно мало, чтобы не беспокоиться. • CompCPU - упрощённое представление настроек LZMA2, которые влияют на скорость сжатия. Размер словаря тоже влияет на скорость, так что, хотя CompCPU одинаков для уровней -6 ... -9, более высокие уровни всё равно склонны быть немного медленнее. Чтобы получить ещё более медленное и, возможно, лучшее сжатие, см. --extreme. • CompMem - требования к памяти компрессора в однопоточном режиме. Это может немного варьироваться между версиями xz. • DecMem - требования к памяти декомпрессора. То есть, настройки сжатия определяют требования к памяти декомпрессора. Точное использование памяти декомпрессором немного больше, чем размер словаря LZMA2, но значения в таблице округлены до следующего полного MiB. Требования к памяти в многопоточном режиме значительно выше, чем в однопоточном. С значением --block-size по умолчанию, каждый поток требует 3*3*DictSize плюс CompMem или DecMem. Например, четыре потока с пресетом -6 требуют 660–670 MiB памяти. -e, --extreme Использовать более медленный вариант выбранного пресета уровня сжатия (-0 ... -9), чтобы, возможно, получить немного лучший коэффициент сжатия, но с неудачей это может сделать хуже. Использование памяти декомпрессора не затрагивается, но использование памяти компрессора немного увеличивается при пресетах -0 ... -3. Поскольку есть два пресета с размерами словарей 4 MiB и 8 MiB, пресеты -3e и -5e используют немного более быстрые настройки (нижний CompCPU), чем -4e и -6e соответственно. Таким образом, ни два пресета не идентичны. tab(;); c c c c c n n n n n. Preset;DictSize;CompCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB Например, всего четыре пресета используют словарь 8 MiB, и их порядок от самого быстрого к самому медленному - -5, -6, -5e и -6e. --fast --best Эти - это вводящие в заблуждение псевдонимы для -0 и -9 соответственно. Они предоставлены только для обратной совместимости с LZMA Utils. Избегайте использования этих опций. --block-size=size При сжатии в формат .xz, разделить входные данные на блоки по size байт. Блоки сжимаются независимо друг от друга, что помогает с многопоточностью и делает возможной ограниченную случайную доступную распаковку. Эта опция обычно используется для переопределения размера блока по умолчанию в многопоточном режиме, но её можно использовать и в однопоточном режиме. В многопоточном режиме примерно трижды size байт будет выделено в каждом потоке для буферизации входа и вывода. Размер по умолчанию - три раза размер словаря LZMA2 или 1 MiB, в зависимости от того, что больше. Обычно хорошее значение - 2–4 раза размер словаря LZMA2 или хотя бы 1 MiB. Использование size меньше, чем размер словаря LZMA2 - трата ОЗУ, поскольку буфер словаря LZMA2 никогда не будет полностью использован. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Эта информация о размере необходима для многопоточной распаковки. В однопоточном режиме разделение на блоки по умолчанию не выполняется. Установка этой опции не влияет на использование памяти. Информация о размере не хранится в заголовках блоков, поэтому файлы, созданные в однопоточном режиме, не будут идентичны файлам, созданным в многопоточном режиме. Отсутствие информации о размере также означает, что xz не сможет распаковывать файлы в многопоточном режиме. --block-list=items При сжатии в формат .xz, начать новый блок с необязательной пользовательской цепочкой фильтров после указанных интервалов несжатых данных. items - это список, разделённый запятыми. Каждый элемент состоит из необязательного номера цепочки фильтров от 0 до 9, за которым следует двоеточие (:) и требуемый размер несжатых данных. Пропуск элемента (две или более последовательных запятых) - это сокращение для использования размера и фильтров предыдущего элемента. Если входной файл больше, чем сумма размеров в items, последний элемент повторяется до конца файла. Специальное значение 0 может использоваться как последний размер, чтобы указать, что остаток файла должен быть закодирован как один блок. Альтернативную цепочку фильтров для каждого блока можно указать в сочетании с опциями --filters1=filters ... --filters9=filters. Эти опции определяют цепочки фильтров с идентификатором от 1 до 9. Цепочка фильтров 0 можно использовать для ссылки на цепочку фильтров по умолчанию, которая такая же, как и без указания цепочки фильтров. Идентификатор цепочки фильтров можно использовать перед несжатым размером, за которым следует двоеточие (:). Например, если указать --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB, то блоки будут созданы с использованием: • Цепочки фильтров, указанной в --filters1 и 2 MiB входа. • Цепочки фильтров, указанной в --filters3 и 2 MiB входа. • Цепочки фильтров, указанной в --filters2 и 4 MiB входа. • Цепочки фильтров, указанной в --filters2 и 4 MiB входа. • Цепочки фильтров по умолчанию и 2 MiB входа. • Цепочки фильтров по умолчанию и 4 MiB входа для каждого блока до конца входа. Если указать размер, превышающий размер блока кодера (либо значение по умолчанию в многопоточном режиме, либо значение, указанное с --block-size=size), кодер создаст дополнительные блоки, сохраняя границы, указанные в items. Например, если указать --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB и входной файл - 80 MiB, получим 11 блоков: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10 и 1 MiB. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Это не делается в однопоточном режиме, поэтому закодированный вывод не будет идентичен многопоточному режиму. --flush-timeout=timeout При сжатии, если прошло более timeout миллисекунд (положительное целое число) с предыдущего сброса и чтение дополнительных входных данных заблокировано, все ожидающие входные данные сбрасываются из кодера и становятся доступными в выходном потоке. Это может быть полезно, если xz используется для сжатия данных, которые передаются по сети. Малые значения timeout делают данные доступными на приёмной стороне с малой задержкой, но большие значения дают лучший коэффициент сжатия. Эта функция отключена по умолчанию. Если эта опция указана несколько раз, последняя вступает в силу. Специальное значение timeout 0 может использоваться для явного отключения этой функции. Эта функция недоступна в не-POSIX системах. Эта функция всё ещё экспериментальна. В настоящее время xz не подходит для распаковки потока в реальном времени из-за того, как xz выполняет буферизацию. --memlimit-compress=limit Установить лимит использования памяти для сжатия. Если эта опция указана несколько раз, последняя вступает в силу. Если настройки сжатия превышают лимит, xz попытается скорректировать настройки вниз, чтобы лимит больше не превышался, и выведет уведомление, что автоматическая корректировка была выполнена. Корректировки производятся в следующем порядке: уменьшение количества потоков, переключение в однопоточный режим, если даже один поток в многопоточном режиме превышает лимит, и, наконец, уменьшение размера словаря LZMA2. При сжатии с --format=raw или если указан --no-adjust, может быть уменьшено только количество потоков, поскольку это можно сделать без влияния на сжатый вывод. Если лимит не может быть достигнут даже с корректировками, описанными выше, выводится ошибка, и xz завершится с кодом выхода 1. Лимит может быть указан несколькими способами: • Лимит может быть абсолютным значением в байтах. Использование суффикса целого числа, как MiB, может быть полезным. Пример: --memlimit-compress=80MiB • Лимит может быть указан как процент от общего физического памяти (ОЗУ). Это может быть полезно, особенно при установке переменной окружения XZ_DEFAULTS в скрипте инициализации оболочки, который используется на разных компьютерах. Таким образом лимит автоматически больше на системах с большим количеством памяти. Пример: --memlimit-compress=70% • Лимит может быть сброшен до значения по умолчанию путём установки на 0. В настоящее время это эквивалентно установке лимита на max (нет лимита использования памяти). Для 32-разрядного xz есть специальный случай: если лимит будет больше 4020 MiB, лимит устанавливается на 4020 MiB. На MIPS32 используется 2000 MiB вместо этого. (Значения 0 и max не затрагиваются этим. Аналогичная функция не существует для распаковки.) Это может быть полезно, когда 32-разрядный исполняемый файл имеет доступ к 4 GiB адресного пространства (2 GiB на MIPS32), в то время как надеемся, что в других ситуациях вреда не будет. См. также раздел Использование памяти. --memlimit-decompress=limit Установить лимит использования памяти для распаковки. Это также влияет на режим --list. Если операция невозможна без превышения лимита, xz выведет ошибку, и распаковка файла не удастся. См. --memlimit-compress=limit для возможных способов указания лимита. --memlimit-mt-decompress=limit Установить лимит использования памяти для многопоточной распаковки. Это может повлиять только на количество потоков; это никогда не заставит xz отказаться от распаковки файла. Если limit слишком низкий, чтобы позволить какую-либо многопоточность, лимит игнорируется, и xz продолжит в однопоточном режиме. Обратите внимание, что если также используется --memlimit-decompress, он будет применяться и к однопоточному, и к многопоточному режимам, так что эффективный лимит для многопоточности никогда не будет выше, чем лимит, установленный с --memlimit-decompress. В отличие от других опций лимита использования памяти, --memlimit-mt-decompress=limit имеет системно-специфическое значение по умолчанию. xz --info-memory можно использовать, чтобы увидеть текущее значение. Эта опция и её значение по умолчанию существуют, потому что без какого-либо лимита многопоточный декомпрессор может закончиться выделением безумного количества памяти с некоторыми входными файлами. Если значение лимита по умолчанию слишком низкое на вашей системе, не стесняйтесь увеличить лимит, но никогда не устанавливайте его на значение больше, чем количество usable ОЗУ, поскольку с подходящими входными файлами xz попытается использовать это количество памяти, даже с небольшим количеством потоков. Выход из памяти или свап не улучшит производительность распаковки. См. --memlimit-compress=limit для возможных способов указания лимита. Установка limit на 0 сбрасывает лимит до системно-специфического значения по умолчанию. -M limit, --memlimit=limit, --memory=limit Это эквивалентно указанию --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Вывести ошибку и выйти, если лимит использования памяти не может быть достигнут без корректировки настроек, которые влияют на сжатый вывод. То есть, это предотвращает переключение кодера из многопоточного режима в однопоточный режим и уменьшение размера словаря LZMA2. Даже при использовании этой опции количество потоков может быть уменьшено, чтобы соответствовать лимиту использования памяти, поскольку это не повлияет на сжатый вывод. Автоматическая корректировка всегда отключена при создании сырых потоков (--format=raw). -T threads, --threads=threads Указать количество рабочих потоков. Установка threads на специальное значение 0 заставляет xz использовать до такого количества потоков, сколько поддерживают процессор(ы) системы. Фактическое количество потоков может быть меньше threads, если входной файл недостаточно большой для потоков с заданными настройками или если использование большего количества потоков превысит лимит использования памяти. Однопоточный и многопоточный компрессоры производят разный вывод. Однопоточный компрессор даст наименьший размер файла, но только вывод из многопоточного компрессора можно распаковывать с использованием нескольких потоков. Установка threads на 1 использует однопоточный режим. Установка threads на любое другое значение, включая 0, использует многопоточный компрессор, даже если система поддерживает только один аппаратный поток. (xz 5.2.x использовал однопоточный режим в этой ситуации.) Чтобы использовать многопоточный режим с одним потоком, установите threads на +1. Префикс + не имеет эффекта с другими значениями. Лимит использования памяти всё равно может заставить xz переключиться в однопоточный режим, если не используется --no-adjust. Поддержка префикса + была добавлена в xz 5.4.0. Если запрошено автоматическое количество потоков и не указан лимит использования памяти, будет использован системно-специфический лимит по умолчанию, чтобы, возможно, ограничить количество потоков. Это мягкий лимит в том смысле, что он игнорируется, если количество потоков становится одним, так что мягкий лимит никогда не остановит xz от сжатия или распаковки. Этот лимит по умолчанию не заставит xz переключиться из многопоточного режима в однопоточный режим. Активные лимиты можно увидеть с помощью xz --info-memory. В настоящее время единственный метод потоков - разделение входа на блоки и сжатие их независимо друг от друга. Размер блока по умолчанию зависит от уровня сжатия и может быть переопределён с помощью опции --block-size=size. Многопоточная распаковка работает только на файлах, которые содержат несколько блоков с информацией о размере в заголовках блоков. Все достаточно большие файлы, сжатые в многопоточном режиме, удовлетворяют этому условию, но файлы, сжатые в однопоточном режиме, не удовлетворяют, даже если использовался --block-size=size. Значение threads по умолчанию - 0. В xz 5.4.x и старше значение по умолчанию - 1. Пользовательские цепочки фильтров компрессора Пользовательская цепочка фильтров позволяет указывать настройки сжатия в деталях вместо использования настроек, связанных с пресетами. Когда указана пользовательская цепочка фильтров, опции пресетов (-0 ... -9 и --extreme), указанные ранее в командной строке, забываются. Если опция пресета указана после одной или нескольких опций пользовательской цепочки фильтров, новый пресет вступает в силу, и пользовательские опции цепочки фильтров, указанные ранее, забываются. Цепочка фильтров сравнима с конвейером в командной строке. При сжатии несжатый вход идёт в первый фильтр, чей вывод идёт в следующий фильтр (если он есть). Вывод последнего фильтра записывается в сжатый файл. Максимальное количество фильтров в цепочке - четыре, но обычно цепочка фильтров имеет только один или два фильтра. Многие фильтры имеют ограничения на их положение в цепочке фильтров: некоторые фильтры могут работать только как последний фильтр в цепочке, некоторые только как нефинальный фильтр, а некоторые работают в любом положении в цепочке. В зависимости от фильтра, это ограничение либо inherent к дизайну фильтра, либо существует, чтобы предотвратить проблемы безопасности. Пользовательскую цепочку фильтров можно указать двумя разными способами. Опции --filters=filters и --filters1=filters ... --filters9=filters позволяют указывать всю цепочку фильтров в одной опции с использованием синтаксиса строк фильтров liblzma. Альтернативно, цепочку фильтров можно указать, используя одну или несколько отдельных опций фильтров в порядке, в котором они должны быть в цепочке. То есть, порядок отдельных опций фильтров значим! При декодировании сырых потоков (--format=raw), цепочка фильтров должна быть указана в том же порядке, в котором она была указана при сжатии. Любые отдельные опции фильтра или пресета, указанные до полной опции цепочки (--filters=filters), будут забыты. Отдельные фильтры, указанные после полной опции цепочки, сбросят цепочку фильтров. И полные, и отдельные опции фильтров принимают опции, специфичные для фильтра, в виде списка, разделённого запятыми. Дополнительные запятые в опциях игнорируются. Каждая опция имеет значение по умолчанию, так что укажите только те, которые вы хотите изменить. Чтобы увидеть всю цепочку фильтров и опции, используйте xz -vv (то есть, используйте --verbose дважды). Это работает также для просмотра опций цепочки фильтров, используемых пресетами. --filters=filters Указать полную цепочку фильтров или пресет в одной опции. Каждый фильтр может быть разделён пробелами или двумя дефисами (--). filters может потребоваться заключить в кавычки в командной строке оболочки, чтобы оно анализировалось как одна опция. Чтобы обозначить опции, используйте : или =. Пресет можно предварить - и следовать нулем или более флагами. Единственный поддерживаемый флаг - e для применения тех же опций, что и --extreme. --filters1=filters ... --filters9=filters Указать до девяти дополнительных цепочек фильтров, которые можно использовать с --block-list. Например, при сжатии архива с исполняемыми файлами, за которыми следуют текстовые файлы, часть с исполняемыми файлами может использовать цепочку фильтров с фильтром BCJ, а текстовую часть - только фильтр LZMA2. --filters-help Вывести сообщение помощи, описывающее, как указывать пресеты и пользовательские цепочки фильтров в опциях --filters и --filters1=filters ... --filters9=filters, и выйти успешно. --lzma1[=options] --lzma2[=options] Добавить фильтр LZMA1 или LZMA2 в цепочку фильтров. Эти фильтры можно использовать только как последний фильтр в цепочке. LZMA1 - это устаревший фильтр, который поддерживается почти исключительно из-за устаревшего формата файла .lzma, который поддерживает только LZMA1. LZMA2 - это обновлённая версия LZMA1 для исправления некоторых практических проблем LZMA1. Формат .xz использует LZMA2 и не поддерживает LZMA1 вообще. Скорость сжатия и коэффициенты LZMA1 и LZMA2 практически одинаковы. LZMA1 и LZMA2 делят один и тот же набор опций: preset=preset Сбросить все опции LZMA1 или LZMA2 на preset. Preset состоит из целого числа, за которым может следовать модификаторы пресета в виде одиночной буквы. Целое число может быть от 0 до 9, соответствующее опциям командной строки -0 ... -9. Единственный поддерживаемый модификатор в настоящее время - e, который соответствует --extreme. Если пресет не указан, значения по умолчанию опций LZMA1 или LZMA2 берутся из пресета 6. dict=size Размер словаря (буфера истории) указывает, сколько байт недавно обработанных несжатых данных хранится в памяти. Алгоритм пытается найти повторяющиеся последовательности байт (соответствия) в несжатых данных и заменить их ссылками на данные, currently в словаре. Чем больше словарь, тем выше шанс найти соответствие. Таким образом, увеличение размера словаря обычно улучшает коэффициент сжатия, но словарь больше, чем несжатый файл - трата памяти. Типичный размер словаря - от 64 KiB до 64 MiB. Минимум - 4 KiB. Максимум для сжатия в настоящее время - 1.5 GiB (1536 MiB). Декомпрессор уже поддерживает словари до одного байта меньше 4 GiB, что является максимумом для форматов потоков LZMA1 и LZMA2. Размер словаря и поиск соответствий (mf) вместе определяют использование памяти кодером LZMA1 или LZMA2. Для распаковки требуется тот же (или больший) размер словаря, что и при сжатии, так что использование памяти декомпрессора определяется размером словаря, использованным при сжатии. Заголовки .xz хранят размер словаря либо как 2^n, либо как 2^n + 2^(n-1), так что эти размеры в некоторой степени предпочтительны для сжатия. Другие размеры будут округлены вверх при хранении в заголовках .xz. lc=lc Указать количество битов контекста литерала. Минимум - 0, максимум - 4; значение по умолчанию - 3. Кроме того, сумма lc и lp не должна превышать 4. Все байты, которые не могут быть закодированы как соответствия, кодируются как литералы. То есть, литералы - просто 8-битные байты, которые кодируются по одному. Литеральное кодирование предполагает, что самые высокие lc бит предыдущего несжатого байта коррелируют со следующим байтом. Например, в типичном английском тексте заглавная буква часто followed by строчная буква, и строчная буква обычно followed by другой строчной буквой. В наборе символов US-ASCII самые высокие три бита - 010 для заглавных букв и 011 для строчных букв. Когда lc как минимум 3, буквальное кодирование может использовать это свойство в несжатых данных. Значение по умолчанию (3) обычно хорошее. Если вы хотите максимальное сжатие, протестируйте lc=4. Иногда это помогает немного, а иногда ухудшает сжатие. Если это ухудшает, протестируйте lc=2 тоже. lp=lp Указать количество битов позиции литерала. Минимум - 0, максимум - 4; значение по умолчанию - 0. lp влияет на то, какое выравнивание в несжатых данных предполагается при кодировании литералов. См. pb ниже для получения дополнительной информации о выравнивании. pb=pb Указать количество битов позиции. Минимум - 0, максимум - 4; значение по умолчанию - 2. pb влияет на то, какое выравнивание в несжатых данных предполагается в общем. Значение по умолчанию означает четырёхбайтное выравнивание (2^pb=2^2=4), что часто хороший выбор, когда нет лучших предположений. Когда выравнивание известно, установка pb соответственно может немного уменьшить размер файла. Например, с текстовыми файлами, имеющими выравнивание по одному байту (US-ASCII, ISO-8859-*, UTF-8), установка pb=0 может немного улучшить сжатие. Для текста UTF-16 pb=1 - хороший выбор. Если выравнивание - нечётное число, как 3 байта, pb=0 может быть лучшим выбором. Хотя предполагаемое выравнивание можно скорректировать с pb и lp, LZMA1 и LZMA2 всё равно немного предпочитают 16-байтное выравнивание. Стоит учитывать это при проектировании форматов файлов, которые, вероятно, будут часто сжиматься с LZMA1 или LZMA2. mf=mf Поиск соответствий сильно влияет на скорость кодера, использование памяти и коэффициент сжатия. Обычно поиск соответствий цепочки хэша быстрее, чем поиск соответствий бинарного дерева. Значение по умолчанию зависит от пресета: 0 использует hc3, 1–3 используют hc4, а остальные - bt4. Поддерживаются следующие поиск соответствий. Формулы использования памяти ниже - грубые приближения, которые ближе всего к реальности, когда dict - степень двойки. hc3 Цепочка хэша с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 7.5 (если dict <= 16 MiB); dict * 5.5 + 64 MiB (если dict > 16 MiB) hc4 Цепочка хэша с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 7.5 (если dict <= 32 MiB); dict * 6.5 (если dict > 32 MiB) bt2 Бинарное дерево с хэшированием 2-байтовым Минимальное значение для nice: 2 Использование памяти: dict * 9.5 bt3 Бинарное дерево с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 11.5 (если dict <= 16 MiB); dict * 9.5 + 64 MiB (если dict > 16 MiB) bt4 Бинарное дерево с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 11.5 (если dict <= 32 MiB); dict * 10.5 (если dict > 32 MiB) mode=mode Режим сжатия указывает метод анализа данных, произведённых поиском соответствий. Поддерживаемые режимы - fast и normal. Значение по умолчанию - fast для пресетов 0–3 и normal для пресетов 4–9. Обычно fast используется с поиском соответствий цепочки хэша, а normal - с поиском соответствий бинарного дерева. Это также то, что делают пресеты. nice=nice Указать, что считается хорошей длиной для соответствия. Как только найдено соответствие длиной не менее nice байт, алгоритм перестаёт искать, возможно, лучшие соответствия. nice может быть от 2 до 273 байт. Более высокие значения склонны давать лучший коэффициент сжатия за счёт скорости. Значение по умолчанию зависит от пресета. depth=depth Указать максимальную глубину поиска в поиске соответствий. Значение по умолчанию - специальное значение 0, которое заставляет компрессор определять разумную глубину из mf и nice. Разумная глубина для цепочек хэша - 4–100, а для бинарных деревьев - 16–1000. Использование очень высоких значений для depth может сделать кодер крайне медленным с некоторыми файлами. Избегайте установки depth выше 1000, если вы готовы прервать сжатие в случае, если оно занимает слишком много времени. При декодировании сырых потоков (--format=raw), LZMA2 нужен только размер словаря. LZMA1 также нужен lc, lp и pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Добавить фильтр ветвления/вызова/прыжка (BCJ) в цепочку фильтров. Эти фильтры можно использовать только как нефинальный фильтр в цепочке. Фильтр BCJ преобразует относительные адреса в машинном коде в их абсолютные аналоги. Это не изменяет размер данных, но увеличивает избыточность, что может помочь LZMA2 произвести на 0–15% меньший файл .xz. Фильтры BCJ всегда обратимы, так что использование фильтра BCJ для неправильного типа данных не приведёт к потере данных, хотя это может немного ухудшить коэффициент сжатия. Фильтры BCJ очень быстрые и используют незначительное количество памяти. Эти фильтры BCJ имеют известные проблемы, связанные с коэффициентом сжатия: • Некоторые типы файлов, содержащие исполняемый код (например, объектные файлы, статические библиотеки и модули ядра Linux), имеют адреса в инструкциях, заполненные заполнителями. Эти фильтры BCJ всё равно выполнят преобразование адреса, что сделает сжатие хуже для этих файлов. • Если фильтр BCJ применяется к архиву, возможно, что это сделает коэффициент сжатия хуже, чем без использования фильтра BCJ. Например, если в архиве есть похожие или даже идентичные исполняемые файлы, то фильтрация, вероятно, сделает файлы менее похожими, и, следовательно, сжатие хуже. Содержимое неисполняемых файлов в том же архиве тоже может влиять. На практике нужно попробовать с фильтром BCJ и без него, чтобы увидеть, что лучше в каждой ситуации. Разные наборы инструкций имеют разное выравнивание: исполняемый файл должен быть выровнен по кратному этого значения во входных данных, чтобы фильтр работал. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit или 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte выравнивание лучше PowerPC;4;Big endian only IA-64;16;Itanium SPARC;4; RISC-V;2; Поскольку отфильтрованные фильтром BCJ данные обычно сжимаются с LZMA2, коэффициент сжатия может быть немного улучшен, если опции LZMA2 установлены так, чтобы соответствовать выравниванию выбранного фильтра BCJ. Примеры: • Фильтр IA-64 имеет выравнивание 16 байт, так что pb=4,lp=4,lc=0 хороши с LZMA2 (2^4=16). • Код RISC-V имеет выравнивание 2 или 4 байта в зависимости от того, содержит ли файл 16-битные сжатые инструкции (расширение C). При использовании 16-битных инструкций хороши pb=2,lp=1,lc=3 или pb=1,lp=1,lc=3. При отсутствии 16-битных инструкций лучше pb=2,lp=2,lc=2. readelf -h можно использовать, чтобы проверить, появляется ли "RVC" в строке "Flags". • ARM64 всегда имеет выравнивание 4 байта, так что pb=2,lp=2,lc=2 - лучше. • Фильтр x86 - исключение. Обычно хорошо придерживаться значений по умолчанию LZMA2 (pb=2,lp=0,lc=3) при сжатии исполняемых файлов x86. Все фильтры BCJ поддерживают одни и те же опции: start=offset Указать начальный смещение, которое используется при преобразовании между относительными и абсолютными адресами. Смещение должно быть кратным выравниванию фильтра (см. таблицу выше). Значение по умолчанию - ноль. На практике, значение по умолчанию хорошее; указание пользовательского смещения почти никогда не полезно. --delta[=options] Добавить фильтр Delta в цепочку фильтров. Фильтр Delta можно использовать только как нефинальный фильтр в цепочке. В настоящее время поддерживается только простое вычисление дельты байт. Это может быть полезно при сжатии, например, несжатых растровых изображений или несжатого PCM-аудио. Однако, специальные алгоритмы могут давать значительно лучшие результаты, чем Delta + LZMA2. Это верно, особенно для аудио, которое сжимается быстрее и лучше, например, с flac(1). Поддерживаемые опции: dist=distance Указать расстояние вычисления дельты в байтах. distance должно быть от 1 до 256. Значение по умолчанию - 1. Например, с dist=2 и входом из восьми байт A1 B1 A2 B3 A3 B5 A4 B7, вывод будет A1 B1 01 02 01 02 01 02. Другие опции -q, --quiet Подавить предупреждения и уведомления. Укажите это дважды, чтобы подавить ошибки тоже. Эта опция не влияет на код выхода. То есть, даже если предупреждение было подавлено, код выхода для указания предупреждения всё равно используется. -v, --verbose Быть подробным. Если стандартный вывод ошибок подключён к терминалу, xz отобразит индикатор прогресса. Указание --verbose дважды даст ещё более подробный вывод. Индикатор прогресса показывает следующую информацию: • Процент завершения показывается, если размер входного файла известен. То есть, процент не может быть показан в конвейерах. • Количество сжатых данных, произведённых (при сжатии) или потреблённых (при распаковке). • Количество несжатых данных, потреблённых (при сжатии) или произведённых (при распаковке). • Коэффициент сжатия, который вычисляется путём деления количества сжатых данных, обработанных до сих пор, на количество несжатых данных, обработанных до сих пор. • Скорость сжатия или распаковки. Это измеряется как количество несжатых данных, потреблённых (сжатие) или произведённых (распаковка) в секунду. Она показывается после того, как прошло несколько секунд с момента запуска обработки файла xz. • Прошедшее время в формате M:SS или H:MM:SS. • Оставшееся оценочное время показывается только тогда, когда размер входного файла известен и прошло несколько секунд с момента запуска обработки файла xz. Время показано в менее точном формате, который никогда не имеет двоеточий, например, 2 min 30 s. Когда стандартный вывод ошибок - не терминал, --verbose заставит xz выводить имя файла, сжатый размер, несжатый размер, коэффициент сжатия и, возможно, скорость и прошедшее время в одну строку в стандартный вывод ошибок после сжатия или распаковки файла. Скорость и прошедшее время включаются только, если операция заняла хотя бы несколько секунд. Если операция не завершилась, например, из-за прерывания пользователем, также выводится процент завершения, если размер входного файла известен. -Q, --no-warn Не устанавливать код выхода на 2, даже если обнаружено состояние, заслуживающее предупреждения. Эта опция не влияет на уровень подробности, так что и --quiet, и --no-warn должны быть использованы, чтобы не выводить предупреждения и не изменять код выхода. --robot Выводить сообщения в формате, удобном для разбора машинами. Это предназначено для облегчения написания фронтендов, которые хотят использовать xz вместо liblzma, что может быть в случае с различными скриптами. Вывод с этой опцией включённой предназначен для стабильности между релизами xz. См. раздел ROBOT MODE для деталей. --info-memory Вывести в удобном для чтения человеком формате, сколько физической памяти (ОЗУ) и сколько процессорных потоков, по мнению xz, имеет система, и лимиты использования памяти для сжатия и распаковки, и выйти успешно. -h, --help Вывести сообщение помощи, описывающее наиболее часто используемые опции, и выйти успешно. -H, --long-help Вывести сообщение помощи, описывающее все возможности xz, и выйти успешно. -V, --version Вывести номер версии xz и liblzma в удобном для чтения человеком формате. Для получения вывода, удобного для разбора машинами, укажите --robot перед --version. ROBOT MODE Режим робота активируется опцией --robot. Это делает вывод xz легче для разбора другими программами. В настоящее время --robot поддерживается только вместе с --list, --filters-help, --info-memory и --version. В будущем это будет поддерживаться для сжатия и распаковки. Режим списка xz --robot --list использует вывод, разделённый табуляцией. Первый столбец каждой строки содержит строку, которая указывает тип информации, найденной в этой строке: name Это всегда первая строка при начале списка файла. Второй столбец в строке - имя файла. file Эта строка содержит общую информацию о файле .xz. Эта строка всегда выводится после строки name. stream Эта строка используется только, когда указан --verbose. Здесь столько строк stream, сколько потоков в файле .xz. block Эта строка используется только, когда указан --verbose. Здесь столько строк block, сколько блоков в файле .xz. Строки block показываются после всех строк stream; разные типы строк не чередуются. summary Этот тип строки используется только, когда указан --verbose дважды. Эта строка выводится после всех строк block. Как и строка file, строка summary содержит общую информацию о файле .xz. totals Эта строка всегда последняя строка вывода списка. Она показывает общие счётчики и размеры. Столбцы строк file: 2. Количество потоков в файле 3. Общее количество блоков в потоке(ах) 4. Сжатый размер файла 5. Несжатый размер файла 6. Коэффициент сжатия, например, 0.123. Если коэффициент больше 9.999, выводятся три дефиса (---) вместо коэффициента. 7. Список имён проверок целостности, разделённый запятыми. Следующие строки используются для известных типов проверок: None, CRC32, CRC64 и SHA-256. Для неизвестных типов проверок используется Unknown-N, где N - ID проверки в десятичном формате (одна или две цифры). 8. Общий размер заполнения потока в файле Столбцы строк stream: 2. Номер потока (первый поток - 1) 3. Количество блоков в потоке 4. Сжатый начальный смещение 5. Несжатый начальный смещение 6. Сжатый размер (не включает заполнение потока) 7. Несжатый размер 8. Коэффициент сжатия 9. Имя проверки целостности 10. Размер заполнения потока Столбцы строк block: 2. Номер потока, содержащего этот блок 3. Номер блока относительно начала потока (первый блок - 1) 4. Номер блока относительно начала файла 5. Сжатый начальный смещение относительно начала файла 6. Несжатый начальный смещение относительно начала файла 7. Общий сжатый размер блока (включает заголовки) 8. Несжатый размер 9. Коэффициент сжатия 10. Имя проверки целостности Если указан --verbose дважды, в строках block добавляются дополнительные столбцы. Эти не отображаются с одним --verbose, потому что получение этой информации требует многих поисков и, следовательно, может быть медленно: 11. Значение проверки целостности в шестнадцатеричном формате 12. Размер заголовка блока 13. Флаги блока: c указывает, что сжатый размер присутствует, и u указывает, что несжатый размер присутствует. Если флаг не установлен, дефис (-) показывается вместо этого, чтобы сохранить длину строки фиксированной. Новые флаги могут быть добавлены в конец строки в будущем. 14. Размер фактических сжатых данных в блоке (это исключает заголовок блока, заполнение блока и поля проверки) 15. Количество памяти (в байтах), необходимое для распаковки этого блока с этой версией xz 16. Цепочка фильтров. Обратите внимание, что большинство опций, использованных при сжатии, не могут быть известны, потому что только опции, которые необходимы для распаковки, хранятся в заголовках .xz. Столбцы строк summary: 2. Количество памяти (в байтах), необходимое для распаковки этого файла с этой версией xz 3. yes или no, указывающее, имеют ли все заголовки блоков как сжатый размер, так и несжатый размер, сохранённые в них С версии xz 5.1.2alpha: 4. Минимальная версия xz, необходимая для распаковки файла Столбцы строки totals: 2. Количество потоков 3. Количество блоков 4. Сжатый размер 5. Несжатый размер 6. Средний коэффициент сжатия 7. Список имён проверок целостности, которые присутствовали в файлах, разделённый запятыми 8. Размер заполнения потока 9. Количество файлов. Это здесь, чтобы сохранить порядок предыдущих столбцов таким же, как в строках file. Если указан --verbose дважды, в строке totals добавляются дополнительные столбцы: 10. Максимальное количество памяти (в байтах), необходимое для распаковки файлов с этой версией xz 11. yes или no, указывающее, имеют ли все заголовки блоков как сжатый размер, так и несжатый размер, сохранённые в них С версии xz 5.1.2alpha: 12. Минимальная версия xz, необходимая для распаковки файла Будущие версии могут добавить новые типы строк, и новые столбцы могут быть добавлены к существующим типам строк, но существующие столбцы не будут изменены. Помощь по фильтрам xz --robot --filters-help выводит поддерживаемые фильтры в следующем формате: filter:option=<value>,option=<value>... filter Имя фильтра option Имя опции, специфичной для фильтра value Диапазоны значений целых чисел появляются как <min-max>. Выборы значений строк показаны в < > и разделены символом |. Каждый фильтр выводится на своей строке. Информация о лимите памяти xz --robot --info-memory выводит одну строку с несколькими столбцами, разделёнными табуляцией: 1. Общее количество физической памяти (ОЗУ) в байтах. 2. Лимит использования памяти для сжатия в байтах (--memlimit-compress). Специальное значение 0 указывает значение по умолчанию, которое для однопоточного режима такое же, как отсутствие лимита. 3. Лимит использования памяти для распаковки в байтах (--memlimit-decompress). Специальное значение 0 указывает значение по умолчанию, которое для однопоточного режима такое же, как отсутствие лимита. 4. С версии xz 5.3.4alpha: Использование памяти для многопоточной распаковки в байтах (--memlimit-mt-decompress). Это никогда не ноль, потому что используется системно-специфическое значение по умолчанию, показанное в столбце 5, если не указано явно. Это также никогда не больше значения в столбце 3, даже если указано большее значение с --memlimit-mt-decompress. 5. С версии xz 5.3.4alpha: Системно-специфическое значение лимита использования памяти по умолчанию, которое используется для ограничения количества потоков при сжатии с автоматическим количеством потоков (--threads=0) и не указанным лимитом использования памяти (--memlimit-compress). Это также используется как значение по умолчанию для --memlimit-mt-decompress. 6. С версии xz 5.3.4alpha: Количество доступных процессорных потоков. В будущем вывод xz --robot --info-memory может иметь больше столбцов, но не больше одной строки. Версия xz --robot --version выводит номер версии xz и liblzma в следующем формате: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Основная версия. YYY Дополнительная версия. Чётные числа стабильны. Нечётные числа - альфа- или бета-версии. ZZZ Уровень патча для стабильных релизов или просто счётчик для версий разработки. S Стабильность. 0 - альфа, 1 - бета, и 2 - стабильная. S должно быть всегда 2, когда YYY чётное. XYYYZZZS одинаковы в обоих строках, если xz и liblzma из одного релиза XZ Utils. Примеры: 4.999.9beta - 49990091 и 5.0.0 - 50000002. EXIT STATUS 0 Всё хорошо. 1 Произошла ошибка. 2 Произошло что-то, заслуживающее предупреждения, но реальных ошибок не произошло. Уведомления (не предупреждения или ошибки), выведенные в стандартный вывод ошибок, не влияют на код выхода. ENVIRONMENT xz анализирует списки опций, разделённые пробелами, из переменных окружения XZ_DEFAULTS и XZ_OPT, в этом порядке, перед анализом опций из командной строки. Обратите внимание, что из переменных окружения анализируются только опции; все нефункции игнорируются молча. Анализ выполняется с getopt_long(3), который используется также для аргументов командной строки. XZ_DEFAULTS Пользовательские или системные опции по умолчанию. Обычно это устанавливается в скрипте инициализации оболочки, чтобы включить лимитер использования памяти xz по умолчанию. Исключая скрипты инициализации оболочки и подобные специальные случаи, скрипты никогда не должны устанавливать или сбрасывать XZ_DEFAULTS. XZ_OPT Это для передачи опций xz, когда невозможно установить опции напрямую в командной строке xz. Это случай, когда xz запускается скриптом или инструментом, например, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Скрипты могут использовать XZ_OPT, например, для установки специфических для скрипта опций сжатия по умолчанию. Всё равно рекомендуется позволить пользователям переопределять XZ_OPT, если это разумно. Например, в скриптах sh(1) можно использовать что-то вроде этого: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY Синтаксис командной строки xz практически является надмножеством lzma, unlzma и lzcat из LZMA Utils 4.32.x. В большинстве случаев возможно заменить LZMA Utils на XZ Utils без нарушения существующих скриптов. Однако есть некоторые несовместимости, которые иногда могут вызвать проблемы. Пресеты уровней сжатия Нумерация пресетов уровней сжатия не идентична в xz и LZMA Utils. Самое важное различие - в том, как размеры словарей сопоставляются с разными пресетами. Размер словаря примерно равен использованию памяти декомпрессора. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB Различия в размерах словарей влияют на использование памяти компрессора тоже, но есть некоторые другие различия между LZMA Utils и XZ Utils, которые делают разницу ещё больше: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB Значение пресета по умолчанию в LZMA Utils - -7, в то время как в XZ Utils оно - -6, так что оба используют словарь 8 MiB по умолчанию. Потоковые vs. непотоковые файлы .lzma Несжатый размер файла может быть сохранён в заголовке .lzma. LZMA Utils делает это при сжатии обычных файлов. Альтернатива - отметить, что несжатый размер неизвестен, и использовать маркер конца полезной нагрузки, чтобы указать, где декомпрессор должен остановиться. LZMA Utils использует этот метод, когда несжатый размер неизвестен, что является случаем, например, в конвейерах. xz поддерживает распаковку файлов .lzma с маркером конца полезной нагрузки или без него, но все файлы .lzma, созданные xz, будут использовать маркер конца полезной нагрузки и иметь несжатый размер, отмеченный как неизвестный в заголовке .lzma. Это может быть проблемой в некоторых нераспространённых ситуациях. Например, декомпрессор .lzma в встроенном устройстве может работать только с файлами, которые имеют известный несжатый размер. Если вы столкнётесь с этой проблемой, вам нужно использовать LZMA Utils или LZMA SDK для создания файлов .lzma с известным несжатым размером. Неподдерживаемые файлы .lzma Формат .lzma позволяет значения lc до 8, а lp до 4. LZMA Utils может распаковывать файлы с любым lc и lp, но всегда создаёт файлы с lc=3 и lp=0. Создание файлов с другими lc и lp возможно с xz и с LZMA SDK. Реализация фильтра LZMA1 в liblzma требует, чтобы сумма lc и lp не превышала 4. Таким образом, файлы .lzma, которые превышают это ограничение, не могут быть распакованы с xz. LZMA Utils создаёт только файлы .lzma, которые имеют размер словаря 2^n (степень двойки), но принимает файлы с любым размером словаря. liblzma принимает только файлы .lzma, которые имеют размер словаря 2^n или 2^n + 2^(n-1). Это для уменьшения ложных срабатываний при обнаружении файлов .lzma. Эти ограничения не должны быть проблемой на практике, поскольку практически все файлы .lzma были сжаты с настройками, которые liblzma примет. Завершающий мусор При распаковке LZMA Utils молча игнорирует всё после первого потока .lzma. В большинстве ситуаций это - ошибка. Это также означает, что LZMA Utils не поддерживает распаковку конкатенированных файлов .lzma. Если после первого потока .lzma остались данные, xz считает файл повреждённым, если не используется --single-stream. Это может нарушить неоднозначные скрипты, которые предполагали, что завершающий мусор игнорируется. NOTES Сжатый вывод может варьироваться Точный сжатый вывод, произведённый из одного и того же несжатого входного файла, может варьироваться между версиями XZ Utils, даже если опции сжатия идентичны. Это потому, что кодер может быть улучшен (быстрее или лучше сжатие) без влияния на формат файла. Вывод может варьироваться даже между разными сборками одной версии XZ Utils, если используются разные опции сборки. Вышеуказанное означает, что, как только будет реализован --rsyncable, результирующие файлы не обязательно будут rsyncable, если старые и новые файлы были сжаты с одной версией xz. Эта проблема может быть исправлена, если часть реализации кодера будет заморожена, чтобы сохранить rsyncable вывод стабильным между версиями xz. Встроенные декомпрессоры .xz Встроенные реализации декомпрессора .xz, как XZ Embedded, не обязательно поддерживают файлы, созданные с типами проверок целостности, отличными от none и crc32. Поскольку значение по умолчанию - --check=crc64, вы должны использовать --check=none или --check=crc32 при создании файлов для встроенных систем. За пределами встроенных систем все декомпрессоры формата .xz поддерживают все типы проверок или, по крайней мере, способны распаковывать файл без проверки целостности, если конкретная проверка не поддерживается. XZ Embedded поддерживает фильтры BCJ, но только с смещением начала по умолчанию. EXAMPLES Основы Сжать файл foo в foo.xz с использованием значения уровня сжатия по умолчанию (-6) и удалить foo, если сжатие успешно: xz foo Распаковать bar.xz в bar и не удалять bar.xz, даже если распаковка успешна: xz -dk bar.xz Создать baz.tar.xz с пресетом -4e (-4 --extreme), который медленнее, чем значение по умолчанию -6, но требует меньше памяти для сжатия и распаковки (48 MiB и 5 MiB соответственно): tar cf - baz | xz -4e > baz.tar.xz Смесь сжатых и несжатых файлов может быть распакована в стандартный вывод с одной командой: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Параллельное сжатие многих файлов На GNU и *BSD, find(1) и xargs(1) могут быть использованы для параллелизации сжатия многих файлов: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 Опция -P xargs(1) устанавливает количество параллельных процессов xz. Лучшее значение для опции -n зависит от количества файлов, подлежащих сжатию. Если файлов всего несколько, значение, вероятно, должно быть 1; с десятками тысяч файлов 100 или даже больше может быть подходящим, чтобы уменьшить количество процессов xz, которые xargs(1) в конечном итоге создаст. Опция -T1 для xz здесь, чтобы заставить его работать в однопоточном режиме, потому что xargs(1) используется для контроля количества параллелизации. Режим робота Вычислить, сколько байт в сумме сэкономлено после сжатия нескольких файлов: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' Скрипт может захотеть знать, что он использует достаточно новую версию xz. Следующий скрипт sh(1) проверяет, что номер версии инструмента xz - как минимум 5.0.0. Этот метод совместим со старыми бета-версиями, которые не поддерживали опцию --robot: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Ваша версия xz слишком старая." fi unset XZ_VERSION LIBLZMA_VERSION Установить лимит использования памяти для распаковки с помощью XZ_OPT, но если лимит уже установлен, не увеличивайте его: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Пользовательские цепочки фильтров компрессора Самое простое использование пользовательских цепочек фильтров - настройка пресета LZMA2. Это может быть полезно, потому что пресеты охватывают только подмножество потенциально полезных комбинаций настроек сжатия. Столбцы CompCPU таблиц из описаний опций -0 ... -9 и --extreme полезны при настройке пресетов LZMA2. Вот релевантные части, собранные из этих двух таблиц: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 Если вы знаете, что файл требует довольно большого словаря (например, 32 MiB) для хорошего сжатия, но вы хотите сжимать его быстрее, чем xz -8, пресет с низким значением CompCPU (например, 1) можно изменить, чтобы использовать больший словарь: xz --lzma2=preset=1,dict=32MiB foo.tar С некоторыми файлами указанная выше команда может быть быстрее, чем xz -6, в то время как сжатие значительно лучше. Однако, стоит подчеркнуть, что только некоторые файлы受益 от большого словаря, сохраняя значение CompCPU низким. Самая очевидная ситуация, где большой словарь может сильно помочь, - архив, содержащий очень похожие файлы по несколько мегабайт каждый. Размер словаря должен быть значительно больше, чем любой отдельный файл, чтобы позволить LZMA2 полностью использовать сходства между последовательными файлами. Если очень высокое использование памяти компрессора и декомпрессора допустимо, и файл, подлежащий сжатию, - как минимум несколько сотен мегабайт, может быть полезно использовать даже больший словарь, чем 64 MiB, который использовал бы xz -9: xz -vv --lzma2=dict=192MiB big_foo.tar Использование -vv (--verbose --verbose), как в примере выше, может быть полезным, чтобы увидеть требования к памяти компрессора и декомпрессора. Помните, что использование словаря больше, чем размер несжатого файла - трата памяти, так что указанная выше команда не полезна для маленьких файлов. Иногда время сжатия не имеет значения, но использование памяти декомпрессора должно быть сохранено низким, например, чтобы сделать возможной распаковку файла на встроенной системе. Следующая команда использует -6e (-6 --extreme) как базу и устанавливает словарь только на 64 KiB. Полученный файл может быть распакован с XZ Embedded (поэтому там --check=crc32) с использованием около 100 KiB памяти. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo Если вы хотите выжать как можно больше байт, корректировка количества битов контекста литерала (lc) и количества битов позиции (pb) иногда помогает. Корректировка количества битов позиции литерала (lp) может помочь тоже, но обычно lc и pb важнее. Например, архив исходного кода содержит в основном текст US-ASCII, так что что-то вроде следующего может дать немного (как 0.1%) меньший файл, чем xz -6e (попробуйте также без lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Использование другого фильтра вместе с LZMA2 может улучшить сжатие с некоторыми типами файлов. Например, чтобы сжать библиотеку x86-32 или x86-64 с фильтром BCJ x86: xz --x86 --lzma2 libfoo.so Обратите внимание, что порядок опций фильтра значим. Если --x86 указан после --lzma2, xz выдаст ошибку, потому что не может быть фильтра после LZMA2, и также потому, что фильтр BCJ x86 не может быть использован как последний фильтр в цепочке. Фильтр Delta вместе с LZMA2 может дать хорошие результаты с растровыми изображениями. Он обычно побеждает PNG, который имеет несколько более продвинутых фильтров, чем простая дельта, но использует Deflate для фактического сжатия. Изображение должно быть сохранено в несжатом формате, например, как несжатый TIFF. Параметр расстояния фильтра Delta устанавливается для соответствия количеству байт на пиксель в изображении. Например, 24-битное растровое изображение RGB нуждается в dist=3, и также хорошо передать pb=0 LZMA2 для размещения трёхбайтного выравнивания: xz --delta=dist=3 --lzma2=pb=0 foo.tiff Если несколько изображений были помещены в один архив (например, .tar), фильтр Delta будет работать на нём тоже, пока все изображения имеют одинаковое количество байт на пиксель. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html>
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Compress or decompress .xz and .lzma files SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz is equivalent to xz --decompress. xzcat is equivalent to xz --decompress --stdout. lzma is equivalent to xz --format=lzma. unlzma is equivalent to xz --format=lzma --decompress. lzcat is equivalent to xz --format=lzma --decompress --stdout. When writing scripts that need to decompress files, it is recommended to always use the name xz with appropriate arguments (xz -d or xz -dc) instead of the names unxz and xzcat. DESCRIPTION xz is a general-purpose data compression tool with command line syntax similar to gzip(1) and bzip2(1). The native file format is the .xz format, but the legacy .lzma format used by LZMA Utils and raw com‐ pressed streams with no container format headers are also supported. In addition, decompression of the .lz format used by lzip is supported. xz compresses or decompresses each file according to the selected oper‐ ation mode. If no files are given or file is -, xz reads from standard input and writes the processed data to standard output. xz will refuse (display an error and skip the file) to write compressed data to stan‐ dard output if it is a terminal. Similarly, xz will refuse to read compressed data from standard input if it is a terminal. Unless --stdout is specified, files other than - are written to a new file whose name is derived from the source file name: • When compressing, the suffix of the target file format (.xz or .lzma) is appended to the source filename to get the target file‐ name. • When decompressing, the .xz, .lzma, or .lz suffix is removed from the filename to get the target filename. xz also recognizes the suffixes .txz and .tlz, and replaces them with the .tar suffix. If the target file already exists, an error is displayed and the file is skipped. Unless writing to standard output, xz will display a warning and skip the file if any of the following applies: • File is not a regular file. Symbolic links are not followed, and thus they are not considered to be regular files. • File has more than one hard link. • File has setuid, setgid, or sticky bit set. • The operation mode is set to compress and the file already has a suffix of the target file format (.xz or .txz when compressing to the .xz format, and .lzma or .tlz when compressing to the .lzma for‐ mat). • The operation mode is set to decompress and the file doesn't have a suffix of any of the supported file formats (.xz, .txz, .lzma, .tlz, or .lz). After successfully compressing or decompressing the file, xz copies the owner, group, permissions, access time, and modification time from the source file to the target file. If copying the group fails, the per‐ missions are modified so that the target file doesn't become accessible to users who didn't have permission to access the source file. xz doesn't support copying other metadata like access control lists or ex‐ tended attributes yet. Once the target file has been successfully closed, the source file is removed unless --keep was specified. The source file is never removed if the output is written to standard output or if an error occurs. Sending SIGINFO or SIGUSR1 to the xz process makes it print progress information to standard error. This has only limited use since when standard error is a terminal, using --verbose will display an automati‐ cally updating progress indicator. Memory usage The memory usage of xz varies from a few hundred kilobytes to several gigabytes depending on the compression settings. The settings used when compressing a file determine the memory requirements of the decom‐ pressor. Typically the decompressor needs 5 % to 20 % of the amount of memory that the compressor needed when creating the file. For example, decompressing a file created with xz -9 currently requires 65 MiB of memory. Still, it is possible to have .xz files that require several gigabytes of memory to decompress. Especially users of older systems may find the possibility of very large memory usage annoying. To prevent uncomfortable surprises, xz has a built-in memory usage limiter, which is disabled by default. While some operating systems provide ways to limit the memory usage of processes, relying on it wasn't deemed to be flexible enough (for exam‐ ple, using ulimit(1) to limit virtual memory tends to cripple mmap(2)). The memory usage limiter can be enabled with the command line option --memlimit=limit. Often it is more convenient to enable the limiter by default by setting the environment variable XZ_DEFAULTS, for example, XZ_DEFAULTS=--memlimit=150MiB. It is possible to set the limits sepa‐ rately for compression and decompression by using --memlimit-com‐ press=limit and --memlimit-decompress=limit. Using these two options outside XZ_DEFAULTS is rarely useful because a single run of xz cannot do both compression and decompression and --memlimit=limit (or -M limit) is shorter to type on the command line. If the specified memory usage limit is exceeded when decompressing, xz will display an error and decompressing the file will fail. If the limit is exceeded when compressing, xz will try to scale the settings down so that the limit is no longer exceeded (except when using --for‐ mat=raw or --no-adjust). This way the operation won't fail unless the limit is very small. The scaling of the settings is done in steps that don't match the compression level presets, for example, if the limit is only slightly less than the amount required for xz -9, the settings will be scaled down only a little, not all the way down to xz -8. Concatenation and padding with .xz files It is possible to concatenate .xz files as is. xz will decompress such files as if they were a single .xz file. It is possible to insert padding between the concatenated parts or af‐ ter the last part. The padding must consist of null bytes and the size of the padding must be a multiple of four bytes. This can be useful, for example, if the .xz file is stored on a medium that measures file sizes in 512-byte blocks. Concatenation and padding are not allowed with .lzma files or raw streams. OPTIONS Integer suffixes and special values In most places where an integer argument is expected, an optional suf‐ fix is supported to easily indicate large integers. There must be no space between the integer and the suffix. KiB Multiply the integer by 1,024 (2^10). Ki, k, kB, K, and KB are accepted as synonyms for KiB. MiB Multiply the integer by 1,048,576 (2^20). Mi, m, M, and MB are accepted as synonyms for MiB. GiB Multiply the integer by 1,073,741,824 (2^30). Gi, g, G, and GB are accepted as synonyms for GiB. The special value max can be used to indicate the maximum integer value supported by the option. Operation mode If multiple operation mode options are given, the last one takes ef‐ fect. -z, --compress Compress. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, unxz implies --decompress). After successful compression, the source file is removed unless writing to standard output or --keep was specified. -d, --decompress, --uncompress Decompress. After successful decompression, the source file is removed unless writing to standard output or --keep was speci‐ fied. -t, --test Test the integrity of compressed files. This option is equiva‐ lent to --decompress --stdout except that the decompressed data is discarded instead of being written to standard output. No files are created or removed. -l, --list Print information about compressed files. No uncompressed out‐ put is produced, and no files are created or removed. In list mode, the program cannot read the compressed data from standard input or from other unseekable sources. The default listing shows basic information about files, one file per line. To get more detailed information, use also the --verbose option. For even more information, use --verbose twice, but note that this may be slow, because getting all the extra information requires many seeks. The width of verbose output exceeds 80 characters, so piping the output to, for exam‐ ple, less -S may be convenient if the terminal isn't wide enough. The exact output may vary between xz versions and different lo‐ cales. For machine-readable output, --robot --list should be used. Operation modifiers -k, --keep Don't delete the input files. Since xz 5.2.6, this option also makes xz compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. In earlier versions this was only done with --force. -f, --force This option has several effects: • If the target file already exists, delete it before compress‐ ing or decompressing. • Compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. • When used with --decompress --stdout and xz cannot recognize the type of the source file, copy the source file as is to standard output. This allows xzcat --force to be used like cat(1) for files that have not been compressed with xz. Note that in future, xz might support new compressed file formats, which may make xz decompress more types of files instead of copying them as is to standard output. --format=format can be used to restrict xz to decompress only a single file for‐ mat. -c, --stdout, --to-stdout Write the compressed or decompressed data to standard output in‐ stead of a file. This implies --keep. --single-stream Decompress only the first .xz stream, and silently ignore possi‐ ble remaining input data following the stream. Normally such trailing garbage makes xz display an error. xz never decompresses more than one stream from .lzma files or raw streams, but this option still makes xz ignore the possible trailing data after the .lzma file or raw stream. This option has no effect if the operation mode is not --decom‐ press or --test. --no-sparse Disable creation of sparse files. By default, if decompressing into a regular file, xz tries to make the file sparse if the de‐ compressed data contains long sequences of binary zeros. It also works when writing to standard output as long as standard output is connected to a regular file and certain additional conditions are met to make it safe. Creating sparse files may save disk space and speed up the decompression by reducing the amount of disk I/O. -S .suf, --suffix=.suf When compressing, use .suf as the suffix for the target file in‐ stead of .xz or .lzma. If not writing to standard output and the source file already has the suffix .suf, a warning is dis‐ played and the file is skipped. When decompressing, recognize files with the suffix .suf in ad‐ dition to files with the .xz, .txz, .lzma, .tlz, or .lz suffix. If the source file has the suffix .suf, the suffix is removed to get the target filename. When compressing or decompressing raw streams (--format=raw), the suffix must always be specified unless writing to standard output, because there is no default suffix for raw streams. --files[=file] Read the filenames to process from file; if file is omitted, filenames are read from standard input. Filenames must be ter‐ minated with the newline character. A dash (-) is taken as a regular filename; it doesn't mean standard input. If filenames are given also as command line arguments, they are processed be‐ fore the filenames read from file. --files0[=file] This is identical to --files[=file] except that each filename must be terminated with the null character. Basic file format and compression options -F format, --format=format Specify the file format to compress or decompress: auto This is the default. When compressing, auto is equiva‐ lent to xz. When decompressing, the format of the input file is automatically detected. Note that raw streams (created with --format=raw) cannot be auto-detected. xz Compress to the .xz file format, or accept only .xz files when decompressing. lzma, alone Compress to the legacy .lzma file format, or accept only .lzma files when decompressing. The alternative name alone is provided for backwards compatibility with LZMA Utils. lzip Accept only .lz files when decompressing. Compression is not supported. The .lz format version 0 and the unextended version 1 are supported. Version 0 files were produced by lzip 1.3 and older. Such files aren't common but may be found from file archives as a few source packages were released in this format. People might have old personal files in this format too. Decompression support for the format version 0 was removed in lzip 1.18. lzip 1.4 and later create files in the format version 1. The sync flush marker extension to the format version 1 was added in lzip 1.6. This extension is rarely used and isn't supported by xz (diagnosed as corrupt input). raw Compress or uncompress a raw stream (no headers). This is meant for advanced users only. To decode raw streams, you need use --format=raw and explicitly specify the fil‐ ter chain, which normally would have been stored in the container headers. -C check, --check=check Specify the type of the integrity check. The check is calcu‐ lated from the uncompressed data and stored in the .xz file. This option has an effect only when compressing into the .xz format; the .lzma format doesn't support integrity checks. The integrity check (if any) is verified when the .xz file is decom‐ pressed. Supported check types: none Don't calculate an integrity check at all. This is usu‐ ally a bad idea. This can be useful when integrity of the data is verified by other means anyway. crc32 Calculate CRC32 using the polynomial from IEEE-802.3 (Ethernet). crc64 Calculate CRC64 using the polynomial from ECMA-182. This is the default, since it is slightly better than CRC32 at detecting damaged files and the speed difference is neg‐ ligible. sha256 Calculate SHA-256. This is somewhat slower than CRC32 and CRC64. Integrity of the .xz headers is always verified with CRC32. It is not possible to change or disable it. --ignore-check Don't verify the integrity check of the compressed data when de‐ compressing. The CRC32 values in the .xz headers will still be verified normally. Do not use this option unless you know what you are doing. Pos‐ sible reasons to use this option: • Trying to recover data from a corrupt .xz file. • Speeding up decompression. This matters mostly with SHA-256 or with files that have compressed extremely well. It's rec‐ ommended to not use this option for this purpose unless the file integrity is verified externally in some other way. -0 ... -9 Select a compression preset level. The default is -6. If mul‐ tiple preset levels are specified, the last one takes effect. If a custom filter chain was already specified, setting a com‐ pression preset level clears the custom filter chain. The differences between the presets are more significant than with gzip(1) and bzip2(1). The selected compression settings determine the memory requirements of the decompressor, thus us‐ ing a too high preset level might make it painful to decompress the file on an old system with little RAM. Specifically, it's not a good idea to blindly use -9 for everything like it often is with gzip(1) and bzip2(1). -0 ... -3 These are somewhat fast presets. -0 is sometimes faster than gzip -9 while compressing much better. The higher ones often have speed comparable to bzip2(1) with compa‐ rable or better compression ratio, although the results depend a lot on the type of data being compressed. -4 ... -6 Good to very good compression while keeping decompressor memory usage reasonable even for old systems. -6 is the default, which is usually a good choice for distributing files that need to be decompressible even on systems with only 16 MiB RAM. (-5e or -6e may be worth considering too. See --extreme.) -7 ... -9 These are like -6 but with higher compressor and decom‐ pressor memory requirements. These are useful only when compressing files bigger than 8 MiB, 16 MiB, and 32 MiB, respectively. On the same hardware, the decompression speed is approximately a constant number of bytes of compressed data per second. In other words, the better the compression, the faster the decom‐ pression will usually be. This also means that the amount of uncompressed output produced per second can vary a lot. The following table summarises the features of the presets: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Column descriptions: • DictSize is the LZMA2 dictionary size. It is waste of memory to use a dictionary bigger than the size of the uncompressed file. This is why it is good to avoid using the presets -7 ... -9 when there's no real need for them. At -6 and lower, the amount of memory wasted is usually low enough to not mat‐ ter. • CompCPU is a simplified representation of the LZMA2 settings that affect compression speed. The dictionary size affects speed too, so while CompCPU is the same for levels -6 ... -9, higher levels still tend to be a little slower. To get even slower and thus possibly better compression, see --extreme. • CompMem contains the compressor memory requirements in the single-threaded mode. It may vary slightly between xz ver‐ sions. • DecMem contains the decompressor memory requirements. That is, the compression settings determine the memory require‐ ments of the decompressor. The exact decompressor memory us‐ age is slightly more than the LZMA2 dictionary size, but the values in the table have been rounded up to the next full MiB. Memory requirements of the multi-threaded mode are significantly higher than that of the single-threaded mode. With the default value of --block-size, each thread needs 3*3*DictSize plus Comp‐ Mem or DecMem. For example, four threads with preset -6 needs 660–670 MiB of memory. -e, --extreme Use a slower variant of the selected compression preset level (-0 ... -9) to hopefully get a little bit better compression ra‐ tio, but with bad luck this can also make it worse. Decompres‐ sor memory usage is not affected, but compressor memory usage increases a little at preset levels -0 ... -3. Since there are two presets with dictionary sizes 4 MiB and 8 MiB, the presets -3e and -5e use slightly faster settings (lower CompCPU) than -4e and -6e, respectively. That way no two presets are identical. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB For example, there are a total of four presets that use 8 MiB dictionary, whose order from the fastest to the slowest is -5, -6, -5e, and -6e. --fast --best These are somewhat misleading aliases for -0 and -9, respec‐ tively. These are provided only for backwards compatibility with LZMA Utils. Avoid using these options. --block-size=size When compressing to the .xz format, split the input data into blocks of size bytes. The blocks are compressed independently from each other, which helps with multi-threading and makes lim‐ ited random-access decompression possible. This option is typi‐ cally used to override the default block size in multi-threaded mode, but this option can be used in single-threaded mode too. In multi-threaded mode about three times size bytes will be al‐ located in each thread for buffering input and output. The de‐ fault size is three times the LZMA2 dictionary size or 1 MiB, whichever is more. Typically a good value is 2–4 times the size of the LZMA2 dictionary or at least 1 MiB. Using size less than the LZMA2 dictionary size is waste of RAM because then the LZMA2 dictionary buffer will never get fully used. In multi-threaded mode, the sizes of the blocks are stored in the block headers. This size information is required for multi-threaded decompres‐ sion. In single-threaded mode no block splitting is done by default. Setting this option doesn't affect memory usage. No size infor‐ mation is stored in block headers, thus files created in single- threaded mode won't be identical to files created in multi- threaded mode. The lack of size information also means that xz won't be able decompress the files in multi-threaded mode. --block-list=items When compressing to the .xz format, start a new block with an optional custom filter chain after the given intervals of uncom‐ pressed data. The items are a comma-separated list. Each item consists of an optional filter chain number between 0 and 9 followed by a colon (:) and a required size of uncompressed data. Omitting an item (two or more consecutive commas) is a shorthand to use the size and filters of the previous item. If the input file is bigger than the sum of the sizes in items, the last item is repeated until the end of the file. A special value of 0 may be used as the last size to indicate that the rest of the file should be encoded as a single block. An alternative filter chain for each block can be specified in combination with the --filters1=filters ... --filters9=filters options. These options define filter chains with an identifier between 1–9. Filter chain 0 can be used to refer to the default filter chain, which is the same as not specifying a filter chain. The filter chain identifier can be used before the un‐ compressed size, followed by a colon (:). For example, if one specifies --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB then blocks will be created using: • The filter chain specified by --filters1 and 2 MiB input • The filter chain specified by --filters3 and 2 MiB input • The filter chain specified by --filters2 and 4 MiB input • The filter chain specified by --filters2 and 4 MiB input • The default filter chain and 2 MiB input • The default filter chain and 4 MiB input for every block un‐ til end of input. If one specifies a size that exceeds the encoder's block size (either the default value in threaded mode or the value speci‐ fied with --block-size=size), the encoder will create additional blocks while keeping the boundaries specified in items. For ex‐ ample, if one specifies --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB and the input file is 80 MiB, one will get 11 blocks: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10, and 1 MiB. In multi-threaded mode the sizes of the blocks are stored in the block headers. This isn't done in single-threaded mode, so the encoded output won't be identical to that of the multi-threaded mode. --flush-timeout=timeout When compressing, if more than timeout milliseconds (a positive integer) has passed since the previous flush and reading more input would block, all the pending input data is flushed from the encoder and made available in the output stream. This can be useful if xz is used to compress data that is streamed over a network. Small timeout values make the data available at the receiving end with a small delay, but large timeout values give better compression ratio. This feature is disabled by default. If this option is speci‐ fied more than once, the last one takes effect. The special timeout value of 0 can be used to explicitly disable this fea‐ ture. This feature is not available on non-POSIX systems. This feature is still experimental. Currently xz is unsuitable for decompressing the stream in real time due to how xz does buffering. --memlimit-compress=limit Set a memory usage limit for compression. If this option is specified multiple times, the last one takes effect. If the compression settings exceed the limit, xz will attempt to adjust the settings downwards so that the limit is no longer ex‐ ceeded and display a notice that automatic adjustment was done. The adjustments are done in this order: reducing the number of threads, switching to single-threaded mode if even one thread in multi-threaded mode exceeds the limit, and finally reducing the LZMA2 dictionary size. When compressing with --format=raw or if --no-adjust has been specified, only the number of threads may be reduced since it can be done without affecting the compressed output. If the limit cannot be met even with the adjustments described above, an error is displayed and xz will exit with exit status 1. The limit can be specified in multiple ways: • The limit can be an absolute value in bytes. Using an inte‐ ger suffix like MiB can be useful. Example: --memlimit-com‐ press=80MiB • The limit can be specified as a percentage of total physical memory (RAM). This can be useful especially when setting the XZ_DEFAULTS environment variable in a shell initialization script that is shared between different computers. That way the limit is automatically bigger on systems with more mem‐ ory. Example: --memlimit-compress=70% • The limit can be reset back to its default value by setting it to 0. This is currently equivalent to setting the limit to max (no memory usage limit). For 32-bit xz there is a special case: if the limit would be over 4020 MiB, the limit is set to 4020 MiB. On MIPS32 2000 MiB is used instead. (The values 0 and max aren't affected by this. A similar feature doesn't exist for decompression.) This can be helpful when a 32-bit executable has access to 4 GiB address space (2 GiB on MIPS32) while hopefully doing no harm in other situations. See also the section Memory usage. --memlimit-decompress=limit Set a memory usage limit for decompression. This also affects the --list mode. If the operation is not possible without ex‐ ceeding the limit, xz will display an error and decompressing the file will fail. See --memlimit-compress=limit for possible ways to specify the limit. --memlimit-mt-decompress=limit Set a memory usage limit for multi-threaded decompression. This can only affect the number of threads; this will never make xz refuse to decompress a file. If limit is too low to allow any multi-threading, the limit is ignored and xz will continue in single-threaded mode. Note that if also --memlimit-decompress is used, it will always apply to both single-threaded and multi- threaded modes, and so the effective limit for multi-threading will never be higher than the limit set with --memlimit-decom‐ press. In contrast to the other memory usage limit options, --mem‐ limit-mt-decompress=limit has a system-specific default limit. xz --info-memory can be used to see the current value. This option and its default value exist because without any limit the threaded decompressor could end up allocating an in‐ sane amount of memory with some input files. If the default limit is too low on your system, feel free to increase the limit but never set it to a value larger than the amount of usable RAM as with appropriate input files xz will attempt to use that amount of memory even with a low number of threads. Running out of memory or swapping will not improve decompression perfor‐ mance. See --memlimit-compress=limit for possible ways to specify the limit. Setting limit to 0 resets the limit to the default sys‐ tem-specific value. -M limit, --memlimit=limit, --memory=limit This is equivalent to specifying --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Display an error and exit if the memory usage limit cannot be met without adjusting settings that affect the compressed out‐ put. That is, this prevents xz from switching the encoder from multi-threaded mode to single-threaded mode and from reducing the LZMA2 dictionary size. Even when this option is used the number of threads may be reduced to meet the memory usage limit as that won't affect the compressed output. Automatic adjusting is always disabled when creating raw streams (--format=raw). -T threads, --threads=threads Specify the number of worker threads to use. Setting threads to a special value 0 makes xz use up to as many threads as the pro‐ cessor(s) on the system support. The actual number of threads can be fewer than threads if the input file is not big enough for threading with the given settings or if using more threads would exceed the memory usage limit. The single-threaded and multi-threaded compressors produce dif‐ ferent output. Single-threaded compressor will give the small‐ est file size but only the output from the multi-threaded com‐ pressor can be decompressed using multiple threads. Setting threads to 1 will use the single-threaded mode. Setting threads to any other value, including 0, will use the multi-threaded compressor even if the system supports only one hardware thread. (xz 5.2.x used single-threaded mode in this situation.) To use multi-threaded mode with only one thread, set threads to +1. The + prefix has no effect with values other than 1. A memory usage limit can still make xz switch to single-threaded mode unless --no-adjust is used. Support for the + prefix was added in xz 5.4.0. If an automatic number of threads has been requested and no mem‐ ory usage limit has been specified, then a system-specific de‐ fault soft limit will be used to possibly limit the number of threads. It is a soft limit in sense that it is ignored if the number of threads becomes one, thus a soft limit will never stop xz from compressing or decompressing. This default soft limit will not make xz switch from multi-threaded mode to single- threaded mode. The active limits can be seen with xz --info-memory. Currently the only threading method is to split the input into blocks and compress them independently from each other. The de‐ fault block size depends on the compression level and can be overridden with the --block-size=size option. Threaded decompression only works on files that contain multiple blocks with size information in block headers. All large enough files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size has been used. The default value for threads is 0. In xz 5.4.x and older the default is 1. Custom compressor filter chains A custom filter chain allows specifying the compression settings in de‐ tail instead of relying on the settings associated to the presets. When a custom filter chain is specified, preset options (-0 ... -9 and --extreme) earlier on the command line are forgotten. If a preset op‐ tion is specified after one or more custom filter chain options, the new preset takes effect and the custom filter chain options specified earlier are forgotten. A filter chain is comparable to piping on the command line. When com‐ pressing, the uncompressed input goes to the first filter, whose output goes to the next filter (if any). The output of the last filter gets written to the compressed file. The maximum number of filters in the chain is four, but typically a filter chain has only one or two fil‐ ters. Many filters have limitations on where they can be in the filter chain: some filters can work only as the last filter in the chain, some only as a non-last filter, and some work in any position in the chain. De‐ pending on the filter, this limitation is either inherent to the filter design or exists to prevent security issues. A custom filter chain can be specified in two different ways. The op‐ tions --filters=filters and --filters1=filters ... --filters9=filters allow specifying an entire filter chain in one option using the liblzma filter string syntax. Alternatively, a filter chain can be specified by using one or more individual filter options in the order they are wanted in the filter chain. That is, the order of the individual fil‐ ter options is significant! When decoding raw streams (--format=raw), the filter chain must be specified in the same order as it was speci‐ fied when compressing. Any individual filter or preset options speci‐ fied before the full chain option (--filters=filters) will be forgot‐ ten. Individual filters specified after the full chain option will re‐ set the filter chain. Both the full and individual filter options take filter-specific op‐ tions as a comma-separated list. Extra commas in options are ignored. Every option has a default value, so specify those you want to change. To see the whole filter chain and options, use xz -vv (that is, use --verbose twice). This works also for viewing the filter chain options used by presets. --filters=filters Specify the full filter chain or a preset in a single option. Each filter can be separated by spaces or two dashes (--). fil‐ ters may need to be quoted on the shell command line so it is parsed as a single option. To denote options, use : or =. A preset can be prefixed with a - and followed with zero or more flags. The only supported flag is e to apply the same options as --extreme. --filters1=filters ... --filters9=filters Specify up to nine additional filter chains that can be used with --block-list. For example, when compressing an archive with executable files followed by text files, the executable part could use a filter chain with a BCJ filter and the text part only the LZMA2 filter. --filters-help Display a help message describing how to specify presets and custom filter chains in the --filters and --filters1=filters ... --filters9=filters options, and exit successfully. --lzma1[=options] --lzma2[=options] Add LZMA1 or LZMA2 filter to the filter chain. These filters can be used only as the last filter in the chain. LZMA1 is a legacy filter, which is supported almost solely due to the legacy .lzma file format, which supports only LZMA1. LZMA2 is an updated version of LZMA1 to fix some practical is‐ sues of LZMA1. The .xz format uses LZMA2 and doesn't support LZMA1 at all. Compression speed and ratios of LZMA1 and LZMA2 are practically the same. LZMA1 and LZMA2 share the same set of options: preset=preset Reset all LZMA1 or LZMA2 options to preset. Preset con‐ sist of an integer, which may be followed by single-let‐ ter preset modifiers. The integer can be from 0 to 9, matching the command line options -0 ... -9. The only supported modifier is currently e, which matches --ex‐ treme. If no preset is specified, the default values of LZMA1 or LZMA2 options are taken from the preset 6. dict=size Dictionary (history buffer) size indicates how many bytes of the recently processed uncompressed data is kept in memory. The algorithm tries to find repeating byte se‐ quences (matches) in the uncompressed data, and replace them with references to the data currently in the dictio‐ nary. The bigger the dictionary, the higher is the chance to find a match. Thus, increasing dictionary size usually improves compression ratio, but a dictionary big‐ ger than the uncompressed file is waste of memory. Typical dictionary size is from 64 KiB to 64 MiB. The minimum is 4 KiB. The maximum for compression is cur‐ rently 1.5 GiB (1536 MiB). The decompressor already sup‐ ports dictionaries up to one byte less than 4 GiB, which is the maximum for the LZMA1 and LZMA2 stream formats. Dictionary size and match finder (mf) together determine the memory usage of the LZMA1 or LZMA2 encoder. The same (or bigger) dictionary size is required for decompressing that was used when compressing, thus the memory usage of the decoder is determined by the dictionary size used when compressing. The .xz headers store the dictionary size either as 2^n or 2^n + 2^(n-1), so these sizes are somewhat preferred for compression. Other sizes will get rounded up when stored in the .xz headers. lc=lc Specify the number of literal context bits. The minimum is 0 and the maximum is 4; the default is 3. In addi‐ tion, the sum of lc and lp must not exceed 4. All bytes that cannot be encoded as matches are encoded as literals. That is, literals are simply 8-bit bytes that are encoded one at a time. The literal coding makes an assumption that the highest lc bits of the previous uncompressed byte correlate with the next byte. For example, in typical English text, an upper-case letter is often followed by a lower-case let‐ ter, and a lower-case letter is usually followed by an‐ other lower-case letter. In the US-ASCII character set, the highest three bits are 010 for upper-case letters and 011 for lower-case letters. When lc is at least 3, the literal coding can take advantage of this property in the uncompressed data. The default value (3) is usually good. If you want maxi‐ mum compression, test lc=4. Sometimes it helps a little, and sometimes it makes compression worse. If it makes it worse, test lc=2 too. lp=lp Specify the number of literal position bits. The minimum is 0 and the maximum is 4; the default is 0. Lp affects what kind of alignment in the uncompressed data is assumed when encoding literals. See pb below for more information about alignment. pb=pb Specify the number of position bits. The minimum is 0 and the maximum is 4; the default is 2. Pb affects what kind of alignment in the uncompressed data is assumed in general. The default means four-byte alignment (2^pb=2^2=4), which is often a good choice when there's no better guess. When the alignment is known, setting pb accordingly may reduce the file size a little. For example, with text files having one-byte alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can improve compression slightly. For UTF-16 text, pb=1 is a good choice. If the alignment is an odd number like 3 bytes, pb=0 might be the best choice. Even though the assumed alignment can be adjusted with pb and lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment. It might be worth taking into account when designing file formats that are likely to be often com‐ pressed with LZMA1 or LZMA2. mf=mf Match finder has a major effect on encoder speed, memory usage, and compression ratio. Usually Hash Chain match finders are faster than Binary Tree match finders. The default depends on the preset: 0 uses hc3, 1–3 use hc4, and the rest use bt4. The following match finders are supported. The memory usage formulas below are rough approximations, which are closest to the reality when dict is a power of two. hc3 Hash Chain with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 7.5 (if dict <= 16 MiB); dict * 5.5 + 64 MiB (if dict > 16 MiB) hc4 Hash Chain with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 7.5 (if dict <= 32 MiB); dict * 6.5 (if dict > 32 MiB) bt2 Binary Tree with 2-byte hashing Minimum value for nice: 2 Memory usage: dict * 9.5 bt3 Binary Tree with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 11.5 (if dict <= 16 MiB); dict * 9.5 + 64 MiB (if dict > 16 MiB) bt4 Binary Tree with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 11.5 (if dict <= 32 MiB); dict * 10.5 (if dict > 32 MiB) mode=mode Compression mode specifies the method to analyze the data produced by the match finder. Supported modes are fast and normal. The default is fast for presets 0–3 and nor‐ mal for presets 4–9. Usually fast is used with Hash Chain match finders and normal with Binary Tree match finders. This is also what the presets do. nice=nice Specify what is considered to be a nice length for a match. Once a match of at least nice bytes is found, the algorithm stops looking for possibly better matches. Nice can be 2–273 bytes. Higher values tend to give bet‐ ter compression ratio at the expense of speed. The de‐ fault depends on the preset. depth=depth Specify the maximum search depth in the match finder. The default is the special value of 0, which makes the compressor determine a reasonable depth from mf and nice. Reasonable depth for Hash Chains is 4–100 and 16–1000 for Binary Trees. Using very high values for depth can make the encoder extremely slow with some files. Avoid set‐ ting the depth over 1000 unless you are prepared to in‐ terrupt the compression in case it is taking far too long. When decoding raw streams (--format=raw), LZMA2 needs only the dictionary size. LZMA1 needs also lc, lp, and pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Add a branch/call/jump (BCJ) filter to the filter chain. These filters can be used only as a non-last filter in the filter chain. A BCJ filter converts relative addresses in the machine code to their absolute counterparts. This doesn't change the size of the data but it increases redundancy, which can help LZMA2 to produce 0–15 % smaller .xz file. The BCJ filters are always re‐ versible, so using a BCJ filter for wrong type of data doesn't cause any data loss, although it may make the compression ratio slightly worse. The BCJ filters are very fast and use an in‐ significant amount of memory. These BCJ filters have known problems related to the compression ratio: • Some types of files containing executable code (for example, object files, static libraries, and Linux kernel modules) have the addresses in the instructions filled with filler values. These BCJ filters will still do the address conver‐ sion, which will make the compression worse with these files. • If a BCJ filter is applied on an archive, it is possible that it makes the compression ratio worse than not using a BCJ filter. For example, if there are similar or even identical executables then filtering will likely make the files less similar and thus compression is worse. The contents of non- executable files in the same archive can matter too. In practice one has to try with and without a BCJ filter to see which is better in each situation. Different instruction sets have different alignment: the exe‐ cutable file must be aligned to a multiple of this value in the input data to make the filter work. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit or 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Since the BCJ-filtered data is usually compressed with LZMA2, the compression ratio may be improved slightly if the LZMA2 op‐ tions are set to match the alignment of the selected BCJ filter. Examples: • IA-64 filter has 16-byte alignment so pb=4,lp=4,lc=0 is good with LZMA2 (2^4=16). • RISC-V code has 2-byte or 4-byte alignment depending on whether the file contains 16-bit compressed instructions (the C extension). When 16-bit instructions are used, pb=2,lp=1,lc=3 or pb=1,lp=1,lc=3 is good. When 16-bit in‐ structions aren't present, pb=2,lp=2,lc=2 is the best. read‐ elf -h can be used to check if "RVC" appears on the "Flags" line. • ARM64 is always 4-byte aligned so pb=2,lp=2,lc=2 is the best. • The x86 filter is an exception. It's usually good to stick to LZMA2's defaults (pb=2,lp=0,lc=3) when compressing x86 ex‐ ecutables. All BCJ filters support the same options: start=offset Specify the start offset that is used when converting be‐ tween relative and absolute addresses. The offset must be a multiple of the alignment of the filter (see the ta‐ ble above). The default is zero. In practice, the de‐ fault is good; specifying a custom offset is almost never useful. --delta[=options] Add the Delta filter to the filter chain. The Delta filter can be only used as a non-last filter in the filter chain. Currently only simple byte-wise delta calculation is supported. It can be useful when compressing, for example, uncompressed bitmap images or uncompressed PCM audio. However, special pur‐ pose algorithms may give significantly better results than Delta + LZMA2. This is true especially with audio, which compresses faster and better, for example, with flac(1). Supported options: dist=distance Specify the distance of the delta calculation in bytes. distance must be 1–256. The default is 1. For example, with dist=2 and eight-byte input A1 B1 A2 B3 A3 B5 A4 B7, the output will be A1 B1 01 02 01 02 01 02. Other options -q, --quiet Suppress warnings and notices. Specify this twice to suppress errors too. This option has no effect on the exit status. That is, even if a warning was suppressed, the exit status to indi‐ cate a warning is still used. -v, --verbose Be verbose. If standard error is connected to a terminal, xz will display a progress indicator. Specifying --verbose twice will give even more verbose output. The progress indicator shows the following information: • Completion percentage is shown if the size of the input file is known. That is, the percentage cannot be shown in pipes. • Amount of compressed data produced (compressing) or consumed (decompressing). • Amount of uncompressed data consumed (compressing) or pro‐ duced (decompressing). • Compression ratio, which is calculated by dividing the amount of compressed data processed so far by the amount of uncom‐ pressed data processed so far. • Compression or decompression speed. This is measured as the amount of uncompressed data consumed (compression) or pro‐ duced (decompression) per second. It is shown after a few seconds have passed since xz started processing the file. • Elapsed time in the format M:SS or H:MM:SS. • Estimated remaining time is shown only when the size of the input file is known and a couple of seconds have already passed since xz started processing the file. The time is shown in a less precise format which never has any colons, for example, 2 min 30 s. When standard error is not a terminal, --verbose will make xz print the filename, compressed size, uncompressed size, compres‐ sion ratio, and possibly also the speed and elapsed time on a single line to standard error after compressing or decompressing the file. The speed and elapsed time are included only when the operation took at least a few seconds. If the operation didn't finish, for example, due to user interruption, also the comple‐ tion percentage is printed if the size of the input file is known. -Q, --no-warn Don't set the exit status to 2 even if a condition worth a warn‐ ing was detected. This option doesn't affect the verbosity level, thus both --quiet and --no-warn have to be used to not display warnings and to not alter the exit status. --robot Print messages in a machine-parsable format. This is intended to ease writing frontends that want to use xz instead of li‐ blzma, which may be the case with various scripts. The output with this option enabled is meant to be stable across xz re‐ leases. See the section ROBOT MODE for details. --info-memory Display, in human-readable format, how much physical memory (RAM) and how many processor threads xz thinks the system has and the memory usage limits for compression and decompression, and exit successfully. -h, --help Display a help message describing the most commonly used op‐ tions, and exit successfully. -H, --long-help Display a help message describing all features of xz, and exit successfully -V, --version Display the version number of xz and liblzma in human readable format. To get machine-parsable output, specify --robot before --version. ROBOT MODE The robot mode is activated with the --robot option. It makes the out‐ put of xz easier to parse by other programs. Currently --robot is sup‐ ported only together with --list, --filters-help, --info-memory, and --version. It will be supported for compression and decompression in the future. List mode xz --robot --list uses tab-separated output. The first column of every line has a string that indicates the type of the information found on that line: name This is always the first line when starting to list a file. The second column on the line is the filename. file This line contains overall information about the .xz file. This line is always printed after the name line. stream This line type is used only when --verbose was specified. There are as many stream lines as there are streams in the .xz file. block This line type is used only when --verbose was specified. There are as many block lines as there are blocks in the .xz file. The block lines are shown after all the stream lines; different line types are not interleaved. summary This line type is used only when --verbose was specified twice. This line is printed after all block lines. Like the file line, the summary line contains overall information about the .xz file. totals This line is always the very last line of the list output. It shows the total counts and sizes. The columns of the file lines: 2. Number of streams in the file 3. Total number of blocks in the stream(s) 4. Compressed size of the file 5. Uncompressed size of the file 6. Compression ratio, for example, 0.123. If ratio is over 9.999, three dashes (---) are displayed instead of the ra‐ tio. 7. Comma-separated list of integrity check names. The follow‐ ing strings are used for the known check types: None, CRC32, CRC64, and SHA-256. For unknown check types, Unknown-N is used, where N is the Check ID as a decimal number (one or two digits). 8. Total size of stream padding in the file The columns of the stream lines: 2. Stream number (the first stream is 1) 3. Number of blocks in the stream 4. Compressed start offset 5. Uncompressed start offset 6. Compressed size (does not include stream padding) 7. Uncompressed size 8. Compression ratio 9. Name of the integrity check 10. Size of stream padding The columns of the block lines: 2. Number of the stream containing this block 3. Block number relative to the beginning of the stream (the first block is 1) 4. Block number relative to the beginning of the file 5. Compressed start offset relative to the beginning of the file 6. Uncompressed start offset relative to the beginning of the file 7. Total compressed size of the block (includes headers) 8. Uncompressed size 9. Compression ratio 10. Name of the integrity check If --verbose was specified twice, additional columns are included on the block lines. These are not displayed with a single --verbose, be‐ cause getting this information requires many seeks and can thus be slow: 11. Value of the integrity check in hexadecimal 12. Block header size 13. Block flags: c indicates that compressed size is present, and u indicates that uncompressed size is present. If the flag is not set, a dash (-) is shown instead to keep the string length fixed. New flags may be added to the end of the string in the future. 14. Size of the actual compressed data in the block (this ex‐ cludes the block header, block padding, and check fields) 15. Amount of memory (in bytes) required to decompress this block with this xz version 16. Filter chain. Note that most of the options used at com‐ pression time cannot be known, because only the options that are needed for decompression are stored in the .xz headers. The columns of the summary lines: 2. Amount of memory (in bytes) required to decompress this file with this xz version 3. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 4. Minimum xz version required to decompress the file The columns of the totals line: 2. Number of streams 3. Number of blocks 4. Compressed size 5. Uncompressed size 6. Average compression ratio 7. Comma-separated list of integrity check names that were present in the files 8. Stream padding size 9. Number of files. This is here to keep the order of the ear‐ lier columns the same as on file lines. If --verbose was specified twice, additional columns are included on the totals line: 10. Maximum amount of memory (in bytes) required to decompress the files with this xz version 11. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 12. Minimum xz version required to decompress the file Future versions may add new line types and new columns can be added to the existing line types, but the existing columns won't be changed. Filters help xz --robot --filters-help prints the supported filters in the following format: filter:option=<value>,option=<value>... filter Name of the filter option Name of a filter specific option value Numeric value ranges appear as <min-max>. String value choices are shown within < > and separated by a | character. Each filter is printed on its own line. Memory limit information xz --robot --info-memory prints a single line with multiple tab-sepa‐ rated columns: 1. Total amount of physical memory (RAM) in bytes. 2. Memory usage limit for compression in bytes (--memlimit-compress). A special value of 0 indicates the default setting which for sin‐ gle-threaded mode is the same as no limit. 3. Memory usage limit for decompression in bytes (--memlimit-decom‐ press). A special value of 0 indicates the default setting which for single-threaded mode is the same as no limit. 4. Since xz 5.3.4alpha: Memory usage for multi-threaded decompression in bytes (--memlimit-mt-decompress). This is never zero because a system-specific default value shown in the column 5 is used if no limit has been specified explicitly. This is also never greater than the value in the column 3 even if a larger value has been specified with --memlimit-mt-decompress. 5. Since xz 5.3.4alpha: A system-specific default memory usage limit that is used to limit the number of threads when compressing with an automatic number of threads (--threads=0) and no memory usage limit has been specified (--memlimit-compress). This is also used as the default value for --memlimit-mt-decompress. 6. Since xz 5.3.4alpha: Number of available processor threads. In the future, the output of xz --robot --info-memory may have more columns, but never more than a single line. Version xz --robot --version prints the version number of xz and liblzma in the following format: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Major version. YYY Minor version. Even numbers are stable. Odd numbers are alpha or beta versions. ZZZ Patch level for stable releases or just a counter for develop‐ ment releases. S Stability. 0 is alpha, 1 is beta, and 2 is stable. S should be always 2 when YYY is even. XYYYZZZS are the same on both lines if xz and liblzma are from the same XZ Utils release. Examples: 4.999.9beta is 49990091 and 5.0.0 is 50000002. EXIT STATUS 0 All is good. 1 An error occurred. 2 Something worth a warning occurred, but no actual errors oc‐ curred. Notices (not warnings or errors) printed on standard error don't affect the exit status. ENVIRONMENT xz parses space-separated lists of options from the environment vari‐ ables XZ_DEFAULTS and XZ_OPT, in this order, before parsing the options from the command line. Note that only options are parsed from the en‐ vironment variables; all non-options are silently ignored. Parsing is done with getopt_long(3) which is used also for the command line argu‐ ments. XZ_DEFAULTS User-specific or system-wide default options. Typically this is set in a shell initialization script to enable xz's memory usage limiter by default. Excluding shell initialization scripts and similar special cases, scripts must never set or unset XZ_DE‐ FAULTS. XZ_OPT This is for passing options to xz when it is not possible to set the options directly on the xz command line. This is the case when xz is run by a script or tool, for example, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Scripts may use XZ_OPT, for example, to set script-specific de‐ fault compression options. It is still recommended to allow users to override XZ_OPT if that is reasonable. For example, in sh(1) scripts one may use something like this: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY The command line syntax of xz is practically a superset of lzma, un‐ lzma, and lzcat as found from LZMA Utils 4.32.x. In most cases, it is possible to replace LZMA Utils with XZ Utils without breaking existing scripts. There are some incompatibilities though, which may sometimes cause problems. Compression preset levels The numbering of the compression level presets is not identical in xz and LZMA Utils. The most important difference is how dictionary sizes are mapped to different presets. Dictionary size is roughly equal to the decompressor memory usage. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB The dictionary size differences affect the compressor memory usage too, but there are some other differences between LZMA Utils and XZ Utils, which make the difference even bigger: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB The default preset level in LZMA Utils is -7 while in XZ Utils it is -6, so both use an 8 MiB dictionary by default. Streamed vs. non-streamed .lzma files The uncompressed size of the file can be stored in the .lzma header. LZMA Utils does that when compressing regular files. The alternative is to mark that uncompressed size is unknown and use end-of-payload marker to indicate where the decompressor should stop. LZMA Utils uses this method when uncompressed size isn't known, which is the case, for example, in pipes. xz supports decompressing .lzma files with or without end-of-payload marker, but all .lzma files created by xz will use end-of-payload marker and have uncompressed size marked as unknown in the .lzma header. This may be a problem in some uncommon situations. For exam‐ ple, a .lzma decompressor in an embedded device might work only with files that have known uncompressed size. If you hit this problem, you need to use LZMA Utils or LZMA SDK to create .lzma files with known un‐ compressed size. Unsupported .lzma files The .lzma format allows lc values up to 8, and lp values up to 4. LZMA Utils can decompress files with any lc and lp, but always creates files with lc=3 and lp=0. Creating files with other lc and lp is possible with xz and with LZMA SDK. The implementation of the LZMA1 filter in liblzma requires that the sum of lc and lp must not exceed 4. Thus, .lzma files, which exceed this limitation, cannot be decompressed with xz. LZMA Utils creates only .lzma files which have a dictionary size of 2^n (a power of 2) but accepts files with any dictionary size. liblzma ac‐ cepts only .lzma files which have a dictionary size of 2^n or 2^n + 2^(n-1). This is to decrease false positives when detecting .lzma files. These limitations shouldn't be a problem in practice, since practically all .lzma files have been compressed with settings that liblzma will accept. Trailing garbage When decompressing, LZMA Utils silently ignore everything after the first .lzma stream. In most situations, this is a bug. This also means that LZMA Utils don't support decompressing concatenated .lzma files. If there is data left after the first .lzma stream, xz considers the file to be corrupt unless --single-stream was used. This may break ob‐ scure scripts which have assumed that trailing garbage is ignored. NOTES Compressed output may vary The exact compressed output produced from the same uncompressed input file may vary between XZ Utils versions even if compression options are identical. This is because the encoder can be improved (faster or bet‐ ter compression) without affecting the file format. The output can vary even between different builds of the same XZ Utils version, if different build options are used. The above means that once --rsyncable has been implemented, the result‐ ing files won't necessarily be rsyncable unless both old and new files have been compressed with the same xz version. This problem can be fixed if a part of the encoder implementation is frozen to keep rsynca‐ ble output stable across xz versions. Embedded .xz decompressors Embedded .xz decompressor implementations like XZ Embedded don't neces‐ sarily support files created with integrity check types other than none and crc32. Since the default is --check=crc64, you must use --check=none or --check=crc32 when creating files for embedded systems. Outside embedded systems, all .xz format decompressors support all the check types, or at least are able to decompress the file without veri‐ fying the integrity check if the particular check is not supported. XZ Embedded supports BCJ filters, but only with the default start off‐ set. EXAMPLES Basics Compress the file foo into foo.xz using the default compression level (-6), and remove foo if compression is successful: xz foo Decompress bar.xz into bar and don't remove bar.xz even if decompres‐ sion is successful: xz -dk bar.xz Create baz.tar.xz with the preset -4e (-4 --extreme), which is slower than the default -6, but needs less memory for compression and decom‐ pression (48 MiB and 5 MiB, respectively): tar cf - baz | xz -4e > baz.tar.xz A mix of compressed and uncompressed files can be decompressed to stan‐ dard output with a single command: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Parallel compression of many files On GNU and *BSD, find(1) and xargs(1) can be used to parallelize com‐ pression of many files: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 The -P option to xargs(1) sets the number of parallel xz processes. The best value for the -n option depends on how many files there are to be compressed. If there are only a couple of files, the value should probably be 1; with tens of thousands of files, 100 or even more may be appropriate to reduce the number of xz processes that xargs(1) will eventually create. The option -T1 for xz is there to force it to single-threaded mode, be‐ cause xargs(1) is used to control the amount of parallelization. Robot mode Calculate how many bytes have been saved in total after compressing multiple files: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' A script may want to know that it is using new enough xz. The follow‐ ing sh(1) script checks that the version number of the xz tool is at least 5.0.0. This method is compatible with old beta versions, which didn't support the --robot option: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Set a memory usage limit for decompression using XZ_OPT, but if a limit has already been set, don't increase it: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Custom compressor filter chains The simplest use for custom filter chains is customizing a LZMA2 pre‐ set. This can be useful, because the presets cover only a subset of the potentially useful combinations of compression settings. The CompCPU columns of the tables from the descriptions of the options -0 ... -9 and --extreme are useful when customizing LZMA2 presets. Here are the relevant parts collected from those two tables: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 If you know that a file requires somewhat big dictionary (for example, 32 MiB) to compress well, but you want to compress it quicker than xz -8 would do, a preset with a low CompCPU value (for example, 1) can be modified to use a bigger dictionary: xz --lzma2=preset=1,dict=32MiB foo.tar With certain files, the above command may be faster than xz -6 while compressing significantly better. However, it must be emphasized that only some files benefit from a big dictionary while keeping the CompCPU value low. The most obvious situation, where a big dictionary can help a lot, is an archive containing very similar files of at least a few megabytes each. The dictionary size has to be significantly bigger than any individual file to allow LZMA2 to take full advantage of the similarities between consecutive files. If very high compressor and decompressor memory usage is fine, and the file being compressed is at least several hundred megabytes, it may be useful to use an even bigger dictionary than the 64 MiB that xz -9 would use: xz -vv --lzma2=dict=192MiB big_foo.tar Using -vv (--verbose --verbose) like in the above example can be useful to see the memory requirements of the compressor and decompressor. Re‐ member that using a dictionary bigger than the size of the uncompressed file is waste of memory, so the above command isn't useful for small files. Sometimes the compression time doesn't matter, but the decompressor memory usage has to be kept low, for example, to make it possible to decompress the file on an embedded system. The following command uses -6e (-6 --extreme) as a base and sets the dictionary to only 64 KiB. The resulting file can be decompressed with XZ Embedded (that's why there is --check=crc32) using about 100 KiB of memory. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo If you want to squeeze out as many bytes as possible, adjusting the number of literal context bits (lc) and number of position bits (pb) can sometimes help. Adjusting the number of literal position bits (lp) might help too, but usually lc and pb are more important. For example, a source code archive contains mostly US-ASCII text, so something like the following might give slightly (like 0.1 %) smaller file than xz -6e (try also without lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Using another filter together with LZMA2 can improve compression with certain file types. For example, to compress a x86-32 or x86-64 shared library using the x86 BCJ filter: xz --x86 --lzma2 libfoo.so Note that the order of the filter options is significant. If --x86 is specified after --lzma2, xz will give an error, because there cannot be any filter after LZMA2, and also because the x86 BCJ filter cannot be used as the last filter in the chain. The Delta filter together with LZMA2 can give good results with bitmap images. It should usually beat PNG, which has a few more advanced fil‐ ters than simple delta but uses Deflate for the actual compression. The image has to be saved in uncompressed format, for example, as un‐ compressed TIFF. The distance parameter of the Delta filter is set to match the number of bytes per pixel in the image. For example, 24-bit RGB bitmap needs dist=3, and it is also good to pass pb=0 to LZMA2 to accommodate the three-byte alignment: xz --delta=dist=3 --lzma2=pb=0 foo.tiff If multiple images have been put into a single archive (for example, .tar), the Delta filter will work on that too as long as all images have the same number of bytes per pixel. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html> Tukaani 2024-12-30 XZ(1)
XZMORE(1) XZ Utils XZMORE(1) NAME xzmore, lzmore - просмотр сжатых файлов xz или lzma (текстовых) SYNOPSIS xzmore [file...] lzmore [file...] DESCRIPTION xzmore отображает текст из сжатых файлов в терминале с помощью more(1). Файлы, поддерживаемые xz(1), разархивируются; другие файлы предполагаются уже в несжатом виде. Если файлы не указаны, xzmore читает из стандартного ввода. См. руководство more(1) для команд клавиатуры. Обратите внимание, что прокрутка назад может быть невозможной в зависимости от реализации more(1). Это потому, что xzmore использует pipe для передачи разархивированных данных в more(1). xzless(1) использует less(1), который предоставляет более продвинутые функции. Команда lzmore предоставлена для обратной совместимости с LZMA Utils. ENVIRONMENT PAGER Если PAGER установлен, его значение используется в качестве пейджера вместо more(1). SEE ALSO more(1), xz(1), xzless(1), zmore(1) Tukaani 2024-02-12 XZMORE(1)
XZMORE(1) XZ Utils XZMORE(1) NAME xzmore, lzmore - view xz or lzma compressed (text) files SYNOPSIS xzmore [file...] lzmore [file...] DESCRIPTION xzmore displays text from compressed files to a terminal using more(1). Files supported by xz(1) are decompressed; other files are assumed to be in uncompressed form already. If no files are given, xzmore reads from standard input. See the more(1) manual for the keyboard commands. Note that scrolling backwards might not be possible depending on the implementation of more(1). This is because xzmore uses a pipe to pass the decompressed data to more(1). xzless(1) uses less(1) which pro‐ vides more advanced features. The command lzmore is provided for backward compatibility with LZMA Utils. ENVIRONMENT PAGER If PAGER is set, its value is used as the pager instead of more(1). SEE ALSO more(1), xz(1), xzless(1), zmore(1) Tukaani 2024-02-12 XZMORE(1)
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Сжатие или распаковка файлов .xz и .lzma SYNOPSIS xz [опция...] [файл...] COMMAND ALIASES unxz эквивалентно xz --decompress. xzcat эквивалентно xz --decompress --stdout. lzma эквивалентно xz --format=lzma. unlzma эквивалентно xz --format=lzma --decompress. lzcat эквивалентно xz --format=lzma --decompress --stdout. При написании сценариев, которые требуют распаковки файлов, рекомендуется всегда использовать имя xz с подходящими аргументами (xz -d или xz -dc) вместо имён unxz и xzcat. DESCRIPTION xz - это универсальный инструмент сжатия данных с синтаксисом командной строки, похожим на gzip(1) и bzip2(1). Родной формат файлов - .xz, но также поддерживается устаревший формат .lzma, используемый в LZMA Utils, и необработанные сжатые потоки без заголовков контейнера. Кроме того, поддерживается распаковка формата .lz, используемого lzip. xz сжимает или распаковывает каждый файл в соответствии с выбранным режимом работы. Если файлы не указаны или указан файл -, xz читает из стандартного ввода и записывает обработанные данные в стандартный вывод. xz отказывается (выводит ошибку и пропускает файл) записывать сжатые данные в стандартный вывод, если это терминал. Аналогично, xz отказывается читать сжатые данные из стандартного ввода, если это терминал. Если не указан --stdout, файлы, отличные от -, записываются в новый файл, чьё имя выводится из имени исходного файла: • При сжатии суффикс целевого формата файла (.xz или .lzma) добавляется к имени исходного файла для получения имени целевого файла. • При распаковке суффикс .xz, .lzma или .lz удаляется из имени файла для получения имени целевого файла. xz также распознаёт суффиксы .txz и .tlz и заменяет их на суффикс .tar. Если целевой файл уже существует, выводится ошибка и файл пропускается. Если не запись в стандартный вывод, xz выведет предупреждение и пропустит файл, если выполняется одно из следующих условий: • Файл не является обычным файлом. Символические ссылки не следуют, и поэтому они не считаются обычными файлами. • Файл имеет более одной жёсткой ссылки. • Файл имеет установленными биты setuid, setgid или sticky. • Режим работы установлен на сжатие, и файл уже имеет суффикс целевого формата файла (.xz или .txz при сжатии в формат .xz, и .lzma или .tlz при сжатии в формат .lzma). • Режим работы установлен на распаковку, и файл не имеет суффикса любого из поддерживаемых форматов файлов (.xz, .txz, .lzma, .tlz или .lz). После успешного сжатия или распаковки файла xz копирует владельца, группу, права доступа, время доступа и время изменения из исходного файла в целевой файл. Если копирование группы не удаётся, права доступа изменяются так, чтобы целевой файл не стал доступным для пользователей, у которых не было доступа к исходному файлу. xz пока не поддерживает копирование другой метаданных, такой как списки контроля доступа или расширенные атрибуты. После успешного закрытия целевого файла исходный файл удаляется, если не указан --keep. Исходный файл никогда не удаляется, если вывод записывается в стандартный вывод или если возникает ошибка. Отправка сигнала SIGINFO или SIGUSR1 процессу xz заставляет его вывести информацию о прогрессе в стандартный вывод ошибок. Это имеет ограниченное применение, поскольку если стандартный вывод ошибок является терминалом, использование --verbose отобразит автоматически обновляющийся индикатор прогресса. Использование памяти Использование памяти xz варьируется от нескольких сотен килобайт до нескольких гигабайт в зависимости от настроек сжатия. Настройки, используемые при сжатии файла, определяют требования к памяти декомпрессора. Обычно декомпрессору требуется 5–20% от количества памяти, которое потребовалось компрессору при создании файла. Например, распаковка файла, созданного с xz -9, в настоящее время требует 65 MiB памяти. Тем не менее, возможно наличие файлов .xz, требующих нескольких гигабайт памяти для распаковки. В частности, пользователи старых систем могут найти возможность очень большого использования памяти раздражающей. Чтобы предотвратить неприятные сюрпризы, xz имеет встроенный ограничитель использования памяти, который по умолчанию отключён. Хотя некоторые операционные системы предоставляют способы ограничения использования памяти процессами, полагаться на это не сочли достаточно гибким (например, использование ulimit(1) для ограничения виртуальной памяти склонно к сбою mmap(2)). Ограничитель использования памяти можно включить с помощью опции командной строки --memlimit=limit. Часто удобнее включить ограничитель по умолчанию, установив переменную среды XZ_DEFAULTS, например, XZ_DEFAULTS=--memlimit=150MiB. Возможна установка ограничений отдельно для сжатия и распаковки с помощью --memlimit-compress=limit и --memlimit-decompress=limit. Использование этих двух опций вне XZ_DEFAULTS редко полезно, потому что один запуск xz не может выполнять одновременно сжатие и распаковку, и --memlimit=limit (или -M limit) короче для ввода в командной строке. Если указанный лимит использования памяти превышен при распаковке, xz выведет ошибку, и распаковка файла не удастся. Если лимит превышен при сжатии, xz попытается уменьшить настройки, чтобы лимит больше не превышался (кроме случаев использования --format=raw или --no-adjust). Таким образом, операция не завершится неудачей, если лимит не очень мал. Уменьшение настроек происходит в шагах, которые не соответствуют предустановкам уровня сжатия, например, если лимит немного меньше, чем требуется для xz -9, настройки уменьшатся только немного, а не до xz -8. Конкатенация и заполнение файлов .xz Возможна конкатенация файлов .xz как есть. xz будет распаковывать такие файлы, как будто это один файл .xz. Возможна вставка заполнения между конкатенируемыми частями или после последней части. Заполнение должно состоять из нулевых байтов, и его размер должен быть кратным четырём байтам. Это может быть полезно, например, если файл .xz хранится на носителе, измеряющем размеры файлов в блоках по 512 байт. Конкатенация и заполнение не допускаются для файлов .lzma или необработанных потоков. OPTIONS Суффиксы целых чисел и специальные значения В большинстве мест, где ожидается аргумент целого числа, поддерживается необязательный суффикс для удобного указания больших целых чисел. Между целым числом и суффиксом не должно быть пробела. KiB Умножить целое число на 1 024 (2^10). Ki, k, kB, K и KB принимаются как синонимы для KiB. MiB Умножить целое число на 1 048 576 (2^20). Mi, m, M и MB принимаются как синонимы для MiB. GiB Умножить целое число на 1 073 741 824 (2^30). Gi, g, G и GB принимаются как синонимы для GiB. Специальное значение max может использоваться для указания максимального поддерживаемого целого значения опцией. Режим работы Если указано несколько опций режима работы, последняя вступает в силу. -z, --compress Сжатие. Это режим работы по умолчанию, если ни одна опция режима работы не указана и другой режим не подразумевается из имени команды (например, unxz подразумевает --decompress). После успешного сжатия исходный файл удаляется, если вывод не записывается в стандартный вывод или не указан --keep. -d, --decompress, --uncompress Распаковка. После успешной распаковки исходный файл удаляется, если вывод не записывается в стандартный вывод или не указан --keep. -t, --test Проверить целостность сжатых файлов. Эта опция эквивалентна --decompress --stdout, за исключением того, что распакованные данные отбрасываются вместо записи в стандартный вывод. Файлы не создаются и не удаляются. -l, --list Вывести информацию о сжатых файлах. Не производится распакованный вывод, и файлы не создаются или не удаляются. В режиме списка программа не может читать сжатые данные из стандартного ввода или из других неподвижных источников. По умолчанию список показывает базовую информацию о файлах, один файл на строку. Для получения более детальной информации используйте также опцию --verbose. Для ещё более подробной информации используйте --verbose дважды, но учтите, что это может быть медленно, поскольку получение всей дополнительной информации требует многих поисков. Ширина подробного вывода превышает 80 символов, поэтому перенаправление вывода, например, в less -S, может быть удобным, если терминал недостаточно широкий. Точный вывод может варьироваться между версиями xz и разными локалями. Для машиночитаемого вывода используйте --robot --list. Модификаторы режима работы -k, --keep Не удалять входные файлы. С версии xz 5.2.6 эта опция также заставляет xz сжимать или распаковывать, даже если вход является символической ссылкой на обычный файл, имеет более одной жёсткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. В более ранних версиях это делалось только с --force. -f, --force Эта опция имеет несколько эффектов: • Если целевой файл уже существует, удалить его перед сжатием или распаковкой. • Сжимать или распаковывать, даже если вход является символической ссылкой на обычный файл, имеет более одной жёсткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. • При использовании с --decompress --stdout, если xz не может распознать тип исходного файла, скопировать исходный файл как есть в стандартный вывод. Это позволяет использовать xzcat --force как cat(1) для файлов, которые не были сжаты с xz. Обратите внимание, что в будущем xz может поддерживать новые сжатые форматы файлов, что может заставить xz распаковывать больше типов файлов вместо копирования их как есть в стандартный вывод. --format=format можно использовать для ограничения xz распаковкой только одного формата файла. -c, --stdout, --to-stdout Записывать сжатые или распакованные данные в стандартный вывод вместо файла. Это подразумевает --keep. --single-stream Распаковывать только первый поток .xz и молча игнорировать возможные оставшиеся входные данные после потока. Обычно такие завершающие данные заставляют xz вывести ошибку. xz никогда не распаковывает более одного потока из файлов .lzma или необработанных потоков, но эта опция всё равно заставляет xz игнорировать возможные завершающие данные после файла .lzma или необработанного потока. Эта опция не имеет эффекта, если режим работы не --decompress или --test. --no-sparse Отключить создание разряженных файлов. По умолчанию, при распаковке в обычный файл, xz пытается сделать файл разряженным, если распакованные данные содержат длинные последовательности двоичных нулей. Это также работает при записи в стандартный вывод, если стандартный вывод подключён к обычному файлу и выполняются определённые дополнительные условия для безопасности. Создание разряженных файлов может сэкономить место на диске и ускорить распаковку за счёт уменьшения количества операций ввода/вывода. -S .suf, --suffix=.suf При сжатии использовать .suf в качестве суффикса для целевого файла вместо .xz или .lzma. Если вывод не записывается в стандартный вывод и исходный файл уже имеет суффикс .suf, выводится предупреждение и файл пропускается. При распаковке распознавать файлы с суффиксом .suf в дополнение к файлам с суффиксами .xz, .txz, .lzma, .tlz или .lz. Если исходный файл имеет суффикс .suf, суффикс удаляется для получения имени целевого файла. При сжатии или распаковке необработанных потоков (--format=raw) суффикс всегда должен указываться, если вывод не записывается в стандартный вывод, поскольку для необработанных потоков нет суффикса по умолчанию. --files[=file] Читать имена файлов для обработки из file; если file опущен, имена файлов читаются из стандартного ввода. Имена файлов должны заканчиваться символом новой строки. Точка (-) воспринимается как обычное имя файла; это не означает стандартный ввод. Если имена файлов также указаны как аргументы командной строки, они обрабатываются перед именами, прочитанными из file. --files0[=file] Это идентично --files[=file], за исключением того, что каждое имя файла должно заканчиваться нулевым символом. Базовые опции формата файла и сжатия -F format, --format=format Указать формат файла для сжатия или распаковки: auto Это значение по умолчанию. При сжатии auto эквивалентно xz. При распаковке формат входного файла определяется автоматически. Обратите внимание, что необработанные потоки (созданные с --format=raw) не могут быть автоматически определены. xz Сжимать в формат .xz или принимать только файлы .xz при распаковке. lzma, alone Сжимать в устаревший формат .lzma или принимать только файлы .lzma при распаковке. Альтернативное имя alone предусмотрено для обратной совместимости с LZMA Utils. lzip При распаковке принимать только файлы .lz. Сжатие не поддерживается. Поддерживается версия формата .lz 0 и нерасширенная версия 1. Файлы версии 0 создавались lzip 1.3 и старше. Такие файлы редко встречаются, но могут быть найдены в архивах файлов, поскольку несколько исходных пакетов были выпущены в этом формате. У пользователей могут быть старые личные файлы в этом формате. Поддержка распаковки версии формата 0 была удалена в lzip 1.18. lzip 1.4 и новее создают файлы в формате версии 1. Расширение синхронизированного сброса маркера для версии формата 1 было добавлено в lzip 1.6. Это расширение редко используется и не поддерживается xz (диагностируется как повреждённый ввод). raw Сжимать или распаковывать необработанный поток (без заголовков). Это предназначено только для продвинутых пользователей. Для декодирования необработанных потоков вам нужно использовать --format=raw и явно указать цепочку фильтров, которая обычно хранится в заголовках контейнера. -C check, --check=check Указать тип проверки целостности. Проверка вычисляется из распакованных данных и хранится в файле .xz. Эта опция имеет эффект только при сжатии в формат .xz; формат .lzma не поддерживает проверки целостности. Проверка целостности (если есть) проверяется при распаковке файла .xz. Поддерживаемые типы проверки: none Не вычислять проверку целостности вообще. Это обычно плохая идея. Это может быть полезно, когда целостность данных проверяется другими средствами. crc32 Вычислить CRC32 с использованием полинома из IEEE-802.3 (Ethernet). crc64 Вычислить CRC64 с использованием полинома из ECMA-182. Это значение по умолчанию, поскольку оно немного лучше, чем CRC32, для обнаружения повреждённых файлов, а разница в скорости незначительна. sha256 Вычислить SHA-256. Это немного медленнее, чем CRC32 и CRC64. Целостность заголовков .xz всегда проверяется с CRC32. Изменить или отключить это невозможно. --ignore-check Не проверять проверку целостности сжатых данных при распаковке. Значения CRC32 в заголовках .xz всё равно будут проверены нормально. Не используйте эту опцию, если не знаете, что делаете. Возможные причины использования этой опции: • Попытка восстановления данных из повреждённого файла .xz. • Увеличение скорости распаковки. Это имеет значение в основном с SHA-256 или с файлами, которые сжаты очень хорошо. Рекомендуется не использовать эту опцию для этой цели, если целостность файла проверяется внешне другим способом. -0 ... -9 Выбрать предустановленный уровень сжатия. По умолчанию -6. Если указано несколько предустановленных уровней, последний вступает в силу. Если уже была указана пользовательская цепочка фильтров, установка предустановленного уровня сжатия очищает пользовательскую цепочку фильтров. Различия между предустановками более значительны, чем с gzip(1) и bzip2(1). Выбранные настройки сжатия определяют требования к памяти декомпрессора, поэтому использование слишком высокого предустановленного уровня может сделать распаковку болезненной на старой системе с малым количеством RAM. В частности, не стоит слепо использовать -9 для всего, как часто бывает с gzip(1) и bzip2(1). -0 ... -3 Это относительно быстрые предустановки. -0 иногда быстрее, чем gzip -9, при этом сжимая гораздо лучше. Более высокие обычно имеют скорость, сравнимую с bzip2(1), с соотношением сжатия, сравнимым или лучшим, хотя результаты сильно зависят от типа сжимаемых данных. -4 ... -6 Хорошее до очень хорошего сжатия при разумном использовании памяти декомпрессором, даже для старых систем. -6 - значение по умолчанию, которое обычно является хорошим выбором для распространения файлов, которые должны быть распакованы даже на системах с только 16 MiB RAM. (-5e или -6e также стоит рассмотреть. См. --extreme.) -7 ... -9 Это как -6, но с более высокими требованиями к памяти компрессора и декомпрессора. Эти полезны только при сжатии файлов больше 8 MiB, 16 MiB и 32 MiB соответственно. На одном и том же оборудовании скорость распаковки примерно постоянна в количестве байт сжатых данных в секунду. Другими словами, чем лучше сжатие, тем быстрее обычно будет распаковка. Это также означает, что количество распакованных выходных данных в секунду может сильно варьироваться. В следующей таблице суммируются особенности предустановок: tab(;); c c c c c n n n n n. Preset;DictSize;CompCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Описания столбцов: • DictSize - размер словаря LZMA2. Трата памяти на словарь больше, чем размер распакованного файла, бесполезна. Поэтому не стоит использовать предустановки -7 ... -9, если в них нет реальной нужды. На -6 и ниже, количество потраченной памяти обычно достаточно мало, чтобы не иметь значения. • CompCPU - упрощённое представление настроек LZMA2, влияющих на скорость сжатия. Размер словаря также влияет на скорость, поэтому, хотя CompCPU одинаков для уровней -6 ... -9, более высокие уровни всё равно склонны быть немного медленнее. Чтобы получить ещё более медленное и, возможно, лучшее сжатие, см. --extreme. • CompMem - требования к памяти компрессора в однопоточном режиме. Это может немного варьироваться между версиями xz. • DecMem - требования к памяти декомпрессора. То есть, настройки сжатия определяют требования к памяти декомпрессора. Точное использование памяти декомпрессором немного больше, чем размер словаря LZMA2, но значения в таблице округлены вверх до следующего полного MiB. Требования к памяти в многопоточном режиме значительно выше, чем в однопоточном. С значением --block-size по умолчанию, каждый поток требует 3*3*DictSize плюс CompMem или DecMem. Например, четыре потока с предустановкой -6 требуют 660–670 MiB памяти. -e, --extreme Использовать более медленный вариант выбранного предустановленного уровня сжатия (-0 ... -9), чтобы, возможно, получить немного лучшее соотношение сжатия, но с неудачей это может сделать хуже. Использование памяти декомпрессором не затрагивается, но использование памяти компрессором немного увеличивается на предустановках -0 ... -3. Поскольку существуют две предустановки с размерами словарей 4 MiB и 8 MiB, предустановки -3e и -5e используют немного более быстрые настройки (нижний CompCPU), чем -4e и -6e соответственно. Таким образом, никакие две предустановки не идентичны. tab(;); c c c c c n n n n n. Preset;DictSize;CompCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB Например, всего четыре предустановки используют словарь 8 MiB, и их порядок от самого быстрого к самому медленному - -5, -6, -5e и -6e. --fast --best Эти - несколько вводящие в заблуждение псевдонимы для -0 и -9 соответственно. Они предусмотрены только для обратной совместимости с LZMA Utils. Избегайте использования этих опций. --block-size=size При сжатии в формат .xz разбить входные данные на блоки по size байт. Блоки сжимаются независимо друг от друга, что помогает с многопоточностью и делает возможной ограниченную случайную доступную распаковку. Эта опция обычно используется для переопределения размера блока по умолчанию в многопоточном режиме, но её можно использовать и в однопоточном режиме. В многопоточном режиме примерно три size байта будут выделены в каждом потоке для буферизации ввода и вывода. Значение по умолчанию - три размера словаря LZMA2 или 1 MiB, в зависимости от того, что больше. Обычно хорошее значение - 2–4 раза размер словаря LZMA2 или по крайней мере 1 MiB. Использование size меньше размера словаря LZMA2 - трата RAM, поскольку буфер словаря LZMA2 никогда не будет полностью использован. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Эта информация о размере необходима для многопоточной распаковки. В однопоточном режиме по умолчанию разбиение на блоки не выполняется. Установка этой опции не влияет на использование памяти. Информация о размере не хранится в заголовках блоков, поэтому файлы, созданные в однопоточном режиме, не будут идентичны файлам, созданным в многопоточном режиме. Отсутствие информации о размере также означает, что xz не сможет распаковывать файлы в многопоточном режиме. --block-list=items При сжатии в формат .xz начинать новый блок с необязательной пользовательской цепочкой фильтров после указанных интервалов распакованных данных. items - список, разделённый запятыми. Каждый элемент состоит из необязательного номера цепочки фильтров от 0 до 9, за которым следует двоеточие (:) и обязательный размер распакованных данных. Пропуск элемента (две или более последовательных запятых) - сокращение для использования размера и фильтров предыдущего элемента. Если входной файл больше суммы размеров в items, последний элемент повторяется до конца файла. Специальное значение 0 можно использовать как последний размер, чтобы указать, что остаток файла должен быть закодирован как один блок. Альтернативную цепочку фильтров для каждого блока можно указать в сочетании с опциями --filters1=filters ... --filters9=filters. Эти опции определяют цепочки фильтров с идентификатором от 1 до 9. Цепочка фильтров 0 можно использовать для ссылки на цепочку фильтров по умолчанию, которая является той же, что и без указания цепочки фильтров. Идентификатор цепочки фильтров можно использовать перед размером распакованных данных, за которым следует двоеточие (:). Например, если указать --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB, то блоки будут созданы с использованием: • Цепочки фильтров, указанной в --filters1 и 2 MiB ввода. • Цепочки фильтров, указанной в --filters3 и 2 MiB ввода. • Цепочки фильтров, указанной в --filters2 и 4 MiB ввода. • Цепочки фильтров, указанной в --filters2 и 4 MiB ввода. • Цепочки фильтров по умолчанию и 2 MiB ввода. • Цепочки фильтров по умолчанию и 4 MiB ввода для каждого блока до конца ввода. Если указать размер, превышающий размер блока энкодера (значение по умолчанию в многопоточном режиме или значение, указанное с --block-size=size), энкодер создаст дополнительные блоки, сохраняя границы, указанные в items. Например, если указать --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB и входной файл - 80 MiB, получите 11 блоков: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10 и 1 MiB. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Это не делается в однопоточном режиме, поэтому закодированный вывод не будет идентичен выводу многопоточного режима. --flush-timeout=timeout При сжатии, если прошло более timeout миллисекунд (положительное целое число) с предыдущего сброса и чтение дополнительного ввода заблокировано, все ожидающие входные данные сбрасываются из энкодера и становятся доступными в выходном потоке. Это может быть полезно, если xz используется для сжатия данных, передаваемых по сети. Малые значения timeout делают данные доступными на принимающей стороне с малой задержкой, но большие значения дают лучшее соотношение сжатия. Эта функция отключена по умолчанию. Если эта опция указана несколько раз, последняя вступает в силу. Специальное значение timeout 0 можно использовать для явного отключения этой функции. Эта функция недоступна в не-POSIX системах. Эта функция всё ещё экспериментальна. В настоящее время xz непригодна для распаковки потока в реальном времени из-за того, как xz буферизует данные. --memlimit-compress=limit Установить лимит использования памяти для сжатия. Если эта опция указана несколько раз, последняя вступает в силу. Если настройки сжатия превышают лимит, xz попытается уменьшить настройки вниз, чтобы лимит больше не превышался, и выведет уведомление о том, что автоматическая корректировка была произведена. Корректировки производятся в следующем порядке: уменьшение количества потоков, переключение в однопоточный режим, если даже один поток в многопоточном режиме превышает лимит, и, наконец, уменьшение размера словаря LZMA2. При сжатии с --format=raw или если указан --no-adjust, только количество потоков может быть уменьшено, поскольку это можно сделать без влияния на сжатый вывод. Если лимит невозможно соблюсти даже с корректировками, описанными выше, выводится ошибка, и xz выйдет с кодом выхода 1. Лимит можно указать несколькими способами: • Лимит может быть абсолютным значением в байтах. Использование суффикса целого числа, как MiB, может быть полезным. Пример: --memlimit-compress=80MiB • Лимит может быть указан как процент от общего физического памяти (RAM). Это может быть полезно, особенно при установке переменной среды XZ_DEFAULTS в скрипте инициализации оболочки, который разделяется между разными компьютерами. Таким образом, лимит автоматически становится больше на системах с большим количеством памяти. Пример: --memlimit-compress=70% • Лимит можно сбросить до значения по умолчанию, установив его в 0. В настоящее время это эквивалентно установке лимита в max (без лимита использования памяти). Для 32-разрядного xz есть специальный случай: если лимит превысил бы 4020 MiB, лимит устанавливается в 4020 MiB. На MIPS32 используется 2000 MiB. (Значения 0 и max не затрагиваются. Аналогичная функция не существует для распаковки.) Это может быть полезно, когда 32-разрядный исполняемый файл имеет доступ к 4 GiB адресного пространства (2 GiB на MIPS32), в то время как, надеюсь, не причиняя вреда в других ситуациях. См. также раздел Использование памяти. --memlimit-decompress=limit Установить лимит использования памяти для распаковки. Это также влияет на режим --list. Если операция невозможна без превышения лимита, xz выведет ошибку, и распаковка файла не удастся. См. --memlimit-compress=limit для возможных способов указания лимита. --memlimit-mt-decompress=limit Установить лимит использования памяти для многопоточной распаковки. Это может повлиять только на количество потоков; это никогда не заставит xz отказаться от распаковки файла. Если limit слишком мал, чтобы позволить какое-либо многопоточность, лимит игнорируется, и xz продолжит в однопоточном режиме. Обратите внимание, что если также используется --memlimit-decompress, он всегда применяется и к однопоточному, и к многопоточному режимам, поэтому эффективный лимит для многопоточности никогда не будет выше лимита, установленного с --memlimit-decompress. В отличие от других опций лимита использования памяти, --memlimit-mt-decompress=limit имеет системно-специфическое значение по умолчанию. xz --info-memory можно использовать для просмотра текущего значения. Эта опция и её значение по умолчанию существуют, потому что без какого-либо лимита многопоточный декомпрессор мог бы выделить безумное количество памяти для некоторых входных файлов. Если значение лимита по умолчанию слишком низко на вашей системе, вы можете увеличить лимит, но никогда не устанавливайте его в значение больше, чем количество usable RAM, поскольку с подходящими входными файлами xz попытается использовать это количество памяти даже с небольшим количеством потоков. Выход из памяти или подкачка не улучшат производительность распаковки. См. --memlimit-compress=limit для возможных способов указания лимита. Установка limit в 0 сбрасывает лимит до системно-специфического значения по умолчанию. -M limit, --memlimit=limit, --memory=limit Это эквивалентно указанию --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Вывести ошибку и выйти, если лимит использования памяти невозможно соблюсти без корректировки настроек, влияющих на сжатый вывод. То есть, это предотвращает переключение энкодера из многопоточного режима в однопоточный режим и уменьшение размера словаря LZMA2. Даже при использовании этой опции количество потоков может быть уменьшено для соблюдения лимита использования памяти, поскольку это не влияет на сжатый вывод. Автоматическая корректировка всегда отключена при создании необработанных потоков (--format=raw). -T threads, --threads=threads Указать количество рабочих потоков. Установка threads в специальное значение 0 заставляет xz использовать до столько потоков, сколько процессор(ы) на системе поддерживают. Фактическое количество потоков может быть меньше threads, если входной файл недостаточно большой для многопоточности с заданными настройками или если использование большего количества потоков превысит лимит использования памяти. Однопоточный и многопоточный компрессоры производят разный вывод. Однопоточный компрессор даст самый маленький размер файла, но только вывод из многопоточного компрессора можно распаковывать с использованием нескольких потоков. Установка threads в 1 использует однопоточный режим. Установка threads в любое другое значение, включая 0, будет использовать многопоточный компрессор, даже если система поддерживает только один аппаратный поток. (xz 5.2.x использовал однопоточный режим в этой ситуации.) Чтобы использовать многопоточный режим с только одним потоком, установите threads в +1. Префикс + не имеет эффекта с значениями, отличными от 1. Лимит использования памяти всё равно может заставить xz переключиться в однопоточный режим, если не используется --no-adjust. Поддержка префикса + была добавлена в xz 5.4.0. Если запрошено автоматическое количество потоков и не указан лимит использования памяти, будет использован системно-специфический лимит использования памяти по умолчанию, чтобы, возможно, ограничить количество потоков. Это мягкий лимит в том смысле, что он игнорируется, если количество потоков становится одним, так что мягкий лимит никогда не остановит xz от сжатия или распаковки. Этот лимит по умолчанию не заставит xz переключиться из многопоточного режима в однопоточный режим. Активные лимиты можно увидеть с xz --info-memory. В настоящее время единственный метод многопоточности - разделение входных данных на блоки и сжатие их независимо друг от друга. Размер блока по умолчанию зависит от уровня сжатия и может быть переопределён с опцией --block-size=size. Многопоточная распаковка работает только на файлах, содержащих несколько блоков с информацией о размере в заголовках блоков. Все достаточно большие файлы, сжатые в многопоточном режиме, удовлетворяют этому условию, но файлы, сжатые в однопоточном режиме, нет, даже если использовалась --block-size=size. Значение threads по умолчанию - 0. В xz 5.4.x и старше значение по умолчанию - 1. Пользовательские цепочки фильтров компрессора Пользовательская цепочка фильтров позволяет указывать настройки сжатия подробно, а не полагаться на настройки, связанные с предустановками. Когда указана пользовательская цепочка фильтров, опции предустановок (-0 ... -9 и --extreme), указанные ранее в командной строке, забываются. Если опция предустановки указана после одной или нескольких опций пользовательской цепочки фильтров, новая предустановка вступает в силу, и пользовательские опции цепочки фильтров, указанные ранее, забываются. Цепочка фильтров сравнима с конвейером в командной строке. При сжатии распакованный вход идёт в первый фильтр, чей вывод идёт в следующий фильтр (если есть). Вывод последнего фильтра записывается в сжатый файл. Максимальное количество фильтров в цепочке - четыре, но обычно цепочка фильтров имеет только один или два фильтра. Многие фильтры имеют ограничения на их положение в цепочке фильтров: некоторые фильтры могут работать только как последний фильтр в цепочке, некоторые только как нефинальный фильтр, а некоторые работают в любом положении в цепочке. В зависимости от фильтра это ограничение либо заложено в дизайне фильтра, либо существует для предотвращения проблем безопасности. Пользовательскую цепочку фильтров можно указать двумя разными способами. Опции --filters=filters и --filters1=filters ... --filters9=filters позволяют указывать всю цепочку фильтров в одной опции с синтаксисом строк фильтров liblzma. В качестве альтернативы цепочку фильтров можно указать, используя одну или несколько отдельных опций фильтров в порядке, в котором они должны быть в цепочке. То есть, порядок отдельных опций фильтров имеет значение! При декодировании необработанных потоков (--format=raw) цепочка фильтров должна быть указана в том же порядке, в котором она была указана при сжатии. Любые отдельные фильтры или опции предустановок, указанные перед полной опцией цепочки (--filters=filters), будут забыты. Отдельные фильтры, указанные после полной опции цепочки, сбросят цепочку фильтров. И полные, и отдельные опции фильтров принимают опции, специфичные для фильтра, в виде списка, разделённого запятыми. Дополнительные запятые в опциях игнорируются. Каждая опция имеет значение по умолчанию, так что укажите те, которые вы хотите изменить. Чтобы увидеть всю цепочку фильтров и опции, используйте xz -vv (то есть, используйте --verbose дважды). Это работает также для просмотра опций цепочки фильтров, используемых предустановками. --filters=filters Указать полную цепочку фильтров или предустановку в одной опции. Каждый фильтр может быть разделён пробелами или двумя дефисами (--). filters может потребоваться заключить в кавычки в командной строке оболочки, чтобы оно анализировалось как одна опция. Чтобы обозначить опции, используйте : или =. Предустановку можно предварить - и за ней следовать нулю или более флагам. Единственный поддерживаемый флаг - e, который применяет те же опции, что и --extreme. --filters1=filters ... --filters9=filters Указать до девяти дополнительных цепочек фильтров, которые можно использовать с --block-list. Например, при сжатии архива с исполняемыми файлами, за которыми следуют текстовые файлы, часть с исполняемыми файлами может использовать цепочку фильтров с фильтром BCJ, а часть с текстом - только фильтр LZMA2. --filters-help Вывести сообщение помощи, описывающее, как указывать предустановки и пользовательские цепочки фильтров в опциях --filters и --filters1=filters ... --filters9=filters, и выйти успешно. --lzma1[=options] --lzma2[=options] Добавить фильтр LZMA1 или LZMA2 в цепочку фильтров. Эти фильтры можно использовать только как последний фильтр в цепочке. LZMA1 - устаревший фильтр, который поддерживается почти исключительно из-за устаревшего формата файлов .lzma, который поддерживает только LZMA1. LZMA2 - обновлённая версия LZMA1 для устранения некоторых практических проблем LZMA1. Формат .xz использует LZMA2 и не поддерживает LZMA1 вообще. Скорость сжатия и соотношения LZMA1 и LZMA2 практически одинаковы. LZMA1 и LZMA2 делят один и тот же набор опций: preset=preset Сбросить все опции LZMA1 или LZMA2 на preset. Preset состоит из целого числа, за которым может следовать модификаторы предустановки в виде одиночной буквы. Целое число может быть от 0 до 9, соответствующее опциям командной строки -0 ... -9. Единственный поддерживаемый модификатор в настоящее время - e, который соответствует --extreme. Если предустановка не указана, значения опций LZMA1 или LZMA2 по умолчанию берутся из предустановки 6. dict=size Размер словаря (буфера истории) указывает, сколько байт недавно обработанных распакованных данных хранится в памяти. Алгоритм пытается найти повторяющиеся последовательности байтов (совпадения) в распакованных данных и заменить их ссылками на данные, находящиеся в настоящее время в словаре. Чем больше словарь, тем выше шанс найти совпадение. Таким образом, увеличение размера словаря обычно улучшает соотношение сжатия, но словарь больше, чем распакованный файл - трата памяти. Типичный размер словаря - от 64 KiB до 64 MiB. Минимум - 4 KiB. Максимум для сжатия в настоящее время - 1.5 GiB (1536 MiB). Декомпрессор уже поддерживает словари до одного байта меньше 4 GiB, что является максимумом для форматов потоков LZMA1 и LZMA2. Размер словаря и поискатель совпадений (mf) вместе определяют использование памяти энкодером LZMA1 или LZMA2. Тот же (или больший) размер словаря требуется для распаковки, который использовался при сжатии, таким образом, использование памяти декомпрессором определяется размером словаря, использованного при сжатии. Заголовки .xz хранят размер словаря как 2^n или 2^n + 2^(n-1), так что эти размеры в некоторой степени предпочтительны для сжатия. Другие размеры будут округлены вверх при хранении в заголовках .xz. lc=lc Указать количество битов контекста литералов. Минимум - 0, максимум - 4; значение по умолчанию - 3. Кроме того, сумма lc и lp не должна превышать 4. Все байты, которые не могут быть закодированы как совпадения, кодируются как литералы. То есть, литералы - просто 8-битные байты, которые кодируются по одному. Кодирование литералов предполагает, что высшие lc биты предыдущего распакованного байта коррелируют со следующим байтом. Например, в типичном английском тексте заглавная буква часто следует за строчной буквой, а строчная буква обычно следует за другой строчной буквой. В наборе символов US-ASCII высшие три бита - 010 для заглавных букв и 011 для строчных букв. Когда lc как минимум 3, кодирование литералов может использовать это свойство в распакованных данных. Значение по умолчанию (3) обычно хорошее. Если вы хотите максимальное сжатие, протестируйте lc=4. Иногда это помогает немного, а иногда делает сжатие хуже. Если оно делает хуже, протестируйте lc=2 тоже. lp=lp Указать количество битов позиции литералов. Минимум - 0, максимум - 4; значение по умолчанию - 0. lp влияет на то, какое выравнивание в распакованных данных предполагается при кодировании литералов. См. pb ниже для дополнительной информации о выравнивании. pb=pb Указать количество битов позиции. Минимум - 0, максимум - 4; значение по умолчанию - 2. pb влияет на то, какое выравнивание в распакованных данных предполагается в общем. Значение по умолчанию означает четырёхбайтовое выравнивание (2^pb=2^2=4), что часто является хорошим выбором, когда нет лучшей догадки. Когда выравнивание известно, установка pb соответственно может немного уменьшить размер файла. Например, с текстовыми файлами, имеющими однобайтовое выравнивание (US-ASCII, ISO-8859-*, UTF-8), установка pb=0 может немного улучшить сжатие. Для текста UTF-16 pb=1 - хороший выбор. Если выравнивание - нечётное число, как 3 байта, pb=0 может быть лучшим выбором. Хотя предполагаемое выравнивание можно скорректировать с pb и lp, LZMA1 и LZMA2 всё равно немного предпочитают 16-байтовое выравнивание. Стоит учитывать это при проектировании форматов файлов, которые, вероятно, будут часто сжиматься с LZMA1 или LZMA2. mf=mf Поискатель совпадений сильно влияет на скорость энкодера, использование памяти и соотношение сжатия. Обычно поискатели совпадений Hash Chain быстрее, чем Binary Tree. Значение по умолчанию зависит от предустановки: 0 использует hc3, 1–3 используют hc4, а остальные - bt4. Поддерживаются следующие поискатели совпадений. Формулы использования памяти ниже - приблизительные оценки, которые ближе к реальности, когда dict - степень двойки. hc3 Hash Chain с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 7.5 (если dict <= 16 MiB); dict * 5.5 + 64 MiB (если dict > 16 MiB) hc4 Hash Chain с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 7.5 (если dict <= 32 MiB); dict * 6.5 (если dict > 32 MiB) bt2 Binary Tree с хэшированием 2-байтовым Минимальное значение для nice: 2 Использование памяти: dict * 9.5 bt3 Binary Tree с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 11.5 (если dict <= 16 MiB); dict * 9.5 + 64 MiB (если dict > 16 MiB) bt4 Binary Tree с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 11.5 (если dict <= 32 MiB); dict * 10.5 (если dict > 32 MiB) mode=mode Режим сжатия указывает метод анализа данных, производимых поискателем совпадений. Поддерживаемые режимы - fast и normal. Значение по умолчанию - fast для предустановок 0–3 и normal для предустановок 4–9. Обычно fast используется с поискателями совпадений Hash Chain, а normal с Binary Tree. Это также то, что делают предустановки. nice=nice Указать, какая длина считается приятной для совпадения. Как только найдено совпадение длиной как минимум nice байт, алгоритм перестаёт искать возможные лучшие совпадения. nice может быть 2–273 байта. Более высокие значения склонны давать лучшее соотношение сжатия за счёт скорости. Значение по умолчанию зависит от предустановки. depth=depth Указать максимальную глубину поиска в поискателе совпадений. Значение по умолчанию - специальное значение 0, которое заставляет компрессор определять разумную глубину из mf и nice. Разумная глубина для Hash Chains - 4–100, а для Binary Trees - 16–1000. Использование очень высоких значений для depth может сделать энкодер чрезвычайно медленным для некоторых файлов. Избегайте установки depth выше 1000, если вы готовы прервать сжатие в случае, если оно занимает слишком много времени. При декодировании необработанных потоков (--format=raw) LZMA2 требуется только размер словаря. LZMA1 также требует lc, lp и pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Добавить фильтр ветвления/вызова/перехода (BCJ) в цепочку фильтров. Эти фильтры можно использовать только как нефинальный фильтр в цепочке. Фильтр BCJ преобразует относительные адреса в машинном коде в их абсолютные аналоги. Это не изменяет размер данных, но увеличивает избыточность, что может помочь LZMA2 произвести на 0–15% меньший файл .xz. Фильтры BCJ всегда обратимы, так что использование фильтра BCJ для неправильного типа данных не приводит к потере данных, хотя это может сделать соотношение сжатия немного хуже. Фильтры BCJ очень быстрые и используют незначительное количество памяти. У этих фильтров BCJ известны проблемы, связанные с соотношением сжатия: • Некоторые типы файлов, содержащих исполняемый код (например, объектные файлы, статические библиотеки и модули ядра Linux), имеют адреса в инструкциях, заполненные заполнителями. Эти фильтры BCJ всё равно будут выполнять преобразование адреса, что сделает сжатие хуже для этих файлов. • Если фильтр BCJ применяется к архиву, возможно, что он сделает соотношение сжатия хуже, чем без использования фильтра BCJ. Например, если в архиве есть похожие или даже идентичные исполняемые файлы, фильтрация, вероятно, сделает файлы менее похожими, и таким образом сжатие хуже. Содержимое нефайловых файлов в том же архиве может иметь значение. На практике нужно попробовать с фильтром BCJ и без него, чтобы увидеть, что лучше в каждой ситуации. Разные наборы инструкций имеют разное выравнивание: исполняемый файл должен быть выровнен по кратному этого значения в входных данных, чтобы фильтр работал. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-битный или 64-битный x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-байтовое выравнивание лучше PowerPC;4;Только big endian IA-64;16;Itanium SPARC;4; RISC-V;2; Поскольку отфильтрованные данные BCJ обычно сжимаются с LZMA2, соотношение сжатия может немного улучшиться, если опции LZMA2 установлены так, чтобы соответствовать выравниванию выбранного фильтра BCJ. Примеры: • Фильтр IA-64 имеет 16-байтовое выравнивание, так что pb=4,lp=4,lc=0 хорошо с LZMA2 (2^4=16). • Код RISC-V имеет выравнивание 2 или 4 байта в зависимости от того, содержит ли файл 16-битные сжатые инструкции (расширение C). Когда используются 16-битные инструкции, pb=2,lp=1,lc=3 или pb=1,lp=1,lc=3 хорошо. Когда 16-битные инструкции отсутствуют, pb=2,lp=2,lc=2 - лучшее. readelf -h можно использовать для проверки, появляется ли "RVC" на строке "Flags". • ARM64 всегда имеет выравнивание 4 байта, так что pb=2,lp=2,lc=2 - лучшее. • Фильтр x86 - исключение. Обычно хорошо придерживаться значений по умолчанию LZMA2 (pb=2,lp=0,lc=3) при сжатии исполняемых файлов x86. Все фильтры BCJ поддерживают одни и те же опции: start=offset Указать начальный смещение, которое используется при преобразовании между относительными и абсолютными адресами. Смещение должно быть кратным выравниванию фильтра (см. таблицу выше). Значение по умолчанию - ноль. На практике значение по умолчанию хорошо; указание пользовательского смещения почти никогда не полезно. --delta[=options] Добавить фильтр Delta в цепочку фильтров. Фильтр Delta можно использовать только как нефинальный фильтр в цепочке. В настоящее время поддерживается только простое вычисление дельты по байтам. Это может быть полезно при сжатии, например, несжатых растровых изображений или несжатого PCM-аудио. Однако специальные алгоритмы могут дать значительно лучшие результаты, чем Delta + LZMA2. Это верно, особенно для аудио, которое сжимается быстрее и лучше, например, с flac(1). Поддерживаемые опции: dist=distance Указать расстояние вычисления дельты в байтах. distance должно быть 1–256. Значение по умолчанию - 1. Например, с dist=2 и входом из восьми байт A1 B1 A2 B3 A3 B5 A4 B7 вывод будет A1 B1 01 02 01 02 01 02. Другие опции -q, --quiet Подавлять предупреждения и уведомления. Укажите это дважды, чтобы подавить ошибки тоже. Эта опция не влияет на код выхода. То есть, даже если предупреждение было подавлено, код выхода для указания предупреждения всё равно используется. -v, --verbose Быть подробным. Если стандартный вывод ошибок подключён к терминалу, xz отобразит индикатор прогресса. Указание --verbose дважды даст ещё более подробный вывод. Индикатор прогресса показывает следующую информацию: • Процент завершения отображается, если размер входного файла известен. То есть, процент не может быть отображён в конвейерах. • Количество сжатых данных, произведённых (при сжатии) или потреблённых (при распаковке). • Количество распакованных данных, потреблённых (при сжатии) или произведённых (при распаковке). • Соотношение сжатия, которое вычисляется путём деления количества обработанных сжатых данных на количество обработанных распакованных данных. • Скорость сжатия или распаковки. Это измеряется как количество распакованных данных, потреблённых (сжатие) или произведённых (распаковка) в секунду. Она отображается после того, как прошло несколько секунд с момента запуска xz обработки файла. • Прошедшее время в формате M:SS или H:MM:SS. • Оставшееся оценочное время отображается только когда размер входного файла известен и прошло несколько секунд с момента запуска xz обработки файла. Время отображется в менее точном формате, который никогда не имеет двоеточий, например, 2 min 30 s. Когда стандартный вывод ошибок не является терминалом, --verbose заставит xz вывести имя файла, сжатый размер, распакованный размер, соотношение сжатия и, возможно, скорость и прошедшее время в одной строке в стандартный вывод ошибок после сжатия или распаковки файла. Скорость и прошедшее время включаются только когда операция заняла хотя бы несколько секунд. Если операция не завершилась, например, из-за прерывания пользователем, также выводится процент завершения, если размер входного файла известен. -Q, --no-warn Не устанавливать код выхода в 2, даже если обнаружено условие, заслуживающее предупреждения. Эта опция не влияет на уровень подробности, таким образом, и --quiet, и --no-warn должны быть использованы, чтобы не отображать предупреждения и не изменять код выхода. --robot Выводить сообщения в машиночитаемом формате. Это предназначено для облегчения написания фронтендов, которые хотят использовать xz вместо liblzma, что может быть в случае с различными сценариями. Вывод с этой опцией включённой предназначен для стабильности между выпусками xz. См. раздел ROBOT MODE для деталей. --info-memory Вывести в удобочитаемом формате, сколько физической памяти (RAM) и сколько процессорных потоков, по мнению xz, имеет система, и лимиты использования памяти для сжатия и распаковки, и выйти успешно. -h, --help Вывести сообщение помощи, описывающее наиболее часто используемые опции, и выйти успешно. -H, --long-help Вывести сообщение помощи, описывающее все функции xz, и выйти успешно. -V, --version Вывести номер версии xz и liblzma в удобочитаемом формате. Для получения машиночитаемого вывода укажите --robot перед --version. ROBOT MODE Режим робота активируется с опцией --robot. Он делает вывод xz легче для разбора другими программами. В настоящее время --robot поддерживается только вместе с --list, --filters-help, --info-memory и --version. В будущем он будет поддерживаться для сжатия и распаковки. Режим списка xz --robot --list использует вывод, разделённый табуляцией. Первый столбец каждой строки содержит строку, указывающую тип информации, найденной на этой строке: name Это всегда первая строка при начале списка файла. Второй столбец на строке - имя файла. file Эта строка содержит общую информацию о файле .xz. Эта строка всегда печатается после строки name. stream Эта строка используется только когда указан --verbose. Здесь столько строк stream, сколько потоков в файле .xz. block Эта строка используется только когда указан --verbose. Здесь столько строк block, сколько блоков в файле .xz. Строки block отображаются после всех строк stream; разные типы строк не перемежаются. summary Этот тип строки используется только когда --verbose указан дважды. Эта строка печатается после всех строк block. Как и строка file, строка summary содержит общую информацию о файле .xz. totals Эта строка всегда последняя строка вывода списка. Она показывает общие счётчики и размеры. Столбцы строк file: 2. Количество потоков в файле 3. Общее количество блоков в потоке(ах) 4. Сжатый размер файла 5. Распакованный размер файла 6. Соотношение сжатия, например, 0.123. Если соотношение превышает 9.999, отображаются три дефиса (---) вместо соотношения. 7. Список имён проверок целостности, разделённый запятыми. Следующие строки используются для известных типов проверок: None, CRC32, CRC64 и SHA-256. Для неизвестных типов проверок используется Unknown-N, где N - ID Проверки в десятичном виде (одна или две цифры). 8. Общий размер заполнения потока в файле Столбцы строк stream: 2. Номер потока (первый поток - 1) 3. Количество блоков в потоке 4. Сжатый начальный смещение 5. Распакованный начальный смещение 6. Сжатый размер (не включает заполнение потока) 7. Распакованный размер 8. Соотношение сжатия 9. Имя проверки целостности 10. Размер заполнения потока Столбцы строк block: 2. Номер потока, содержащего этот блок 3. Номер блока относительно начала потока (первый блок - 1) 4. Номер блока относительно начала файла 5. Сжатый начальный смещение относительно начала файла 6. Распакованный начальный смещение относительно начала файла 7. Общий сжатый размер блока (включает заголовки) 8. Распакованный размер 9. Соотношение сжатия 10. Имя проверки целостности Если --verbose указан дважды, в строках block добавляются дополнительные столбцы. Эти не отображаются с одним --verbose, потому что получение этой информации требует многих поисков и, таким образом, может быть медленно: 11. Значение проверки целостности в шестнадцатеричном формате 12. Размер заголовка блока 13. Флаги блока: c указывает, что сжатый размер присутствует, а u указывает, что распакованный размер присутствует. Если флаг не установлен, дефис (-) отображён вместо этого, чтобы сохранить длину строки фиксированной. Новые флаги могут быть добавлены в конец строки в будущем. 14. Размер фактических сжатых данных в блоке (это исключает заголовок блока, заполнение блока и поля проверки) 15. Количество памяти (в байтах), требуемое для распаковки этого блока с этой версией xz 16. Цепочка фильтров. Обратите внимание, что большинство опций, использованных при сжатии, не могут быть известны, потому что только опции, которые необходимы для распаковки, хранятся в заголовках .xz. Столбцы строк summary: 2. Количество памяти (в байтах), требуемое для распаковки этого файла с этой версией xz 3. yes или no, указывающее, имеют ли все заголовки блоков и сжатый, и распакованный размер, сохранённые в них С версии xz 5.1.2alpha: 4. Минимальная версия xz, требуемая для распаковки файла Столбцы строк totals: 2. Количество потоков 3. Количество блоков 4. Сжатый размер 5. Распакованный размер 6. Среднее соотношение сжатия 7. Список имён проверок целостности, разделённый запятыми, которые присутствовали в файлах 8. Размер заполнения потока 9. Количество файлов. Это здесь, чтобы сохранить порядок предыдущих столбцов таким же, как в строках file. Если --verbose указан дважды, в строках totals добавляются дополнительные столбцы: 10. Максимальное количество памяти (в байтах), требуемое для распаковки файлов с этой версией xz 11. yes или no, указывающее, имеют ли все заголовки блоков и сжатый, и распакованный размер, сохранённые в них С версии xz 5.1.2alpha: 12. Минимальная версия xz, требуемая для распаковки файла Будущие версии могут добавить новые типы строк, и новые столбцы могут быть добавлены к существующим типам строк, но существующие столбцы не будут изменены. Помощь по фильтрам xz --robot --filters-help выводит поддерживаемые фильтры в следующем формате: filter:option=<value>,option=<value>... filter Имя фильтра option Имя опции, специфичной для фильтра value Диапазоны значений чисел появляются как <min-max>. Выборы значений строк отображаются в < > и разделяются символом |. Каждый фильтр выводится на своей строке. Информация о лимите памяти xz --robot --info-memory выводит одну строку с несколькими столбцами, разделёнными табуляцией: 1. Общее количество физической памяти (RAM) в байтах. 2. Лимит использования памяти для сжатия в байтах (--memlimit-compress). Специальное значение 0 указывает на настройку по умолчанию, которая для однопоточного режима та же, что и без лимита. 3. Лимит использования памяти для распаковки в байтах (--memlimit-decompress). Специальное значение 0 указывает на настройку по умолчанию, которая для однопоточного режима та же, что и без лимита. 4. С версии xz 5.3.4alpha: Использование памяти для многопоточной распаковки в байтах (--memlimit-mt-decompress). Это никогда не равно нулю, потому что системно-специфическое значение по умолчанию, показанное в столбце 5, используется, если лимит не указан явно. Это также никогда не больше значения в столбце 3, даже если указано большее значение с --memlimit-mt-decompress. 5. С версии xz 5.3.4alpha: Системно-специфическое значение лимита использования памяти по умолчанию, которое используется для ограничения количества потоков при сжатии с автоматическим количеством потоков (--threads=0) и не указанным лимитом использования памяти (--memlimit-compress). Это также используется как значение по умолчанию для --memlimit-mt-decompress. 6. С версии xz 5.3.4alpha: Количество доступных процессорных потоков. В будущем вывод xz --robot --info-memory может иметь больше столбцов, но никогда больше одной строки. Версия xz --robot --version выводит номер версии xz и liblzma в следующем формате: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Основная версия. YYY Дополнительная версия. Чётные числа стабильны. Нечётные числа - альфа- или бета-версии. ZZZ Уровень патча для стабильных выпусков или просто счётчик для версий разработки. S Стабильность. 0 - альфа, 1 - бета, а 2 - стабильная. S должно быть всегда 2, когда YYY чётное. XYYYZZZS одинаковы в обоих строках, если xz и liblzma из одного выпуска XZ Utils. Примеры: 4.999.9beta - 49990091 и 5.0.0 - 50000002. EXIT STATUS 0 Всё в порядке. 1 Произошла ошибка. 2 Произошло что-то, заслуживающее предупреждения, но реальных ошибок не произошло. Уведомления (не предупреждения или ошибки), выведенные в стандартный вывод ошибок, не влияют на код выхода. ENVIRONMENT xz анализирует списки опций, разделённые пробелами, из переменных среды XZ_DEFAULTS и XZ_OPT в этом порядке, перед анализом опций из командной строки. Обратите внимание, что только опции анализируются из переменных среды; все нефопции игнорируются молча. Анализ выполняется с getopt_long(3), который используется также для аргументов командной строки. XZ_DEFAULTS Опции по умолчанию для пользователя или системы. Обычно это устанавливается в скрипте инициализации оболочки для включения ограничителя использования памяти xz по умолчанию. Исключая скрипты инициализации оболочки и подобные специальные случаи, сценарии никогда не должны устанавливать или снимать XZ_DEFAULTS. XZ_OPT Это для передачи опций xz, когда невозможно установить опции напрямую в командной строке xz. Это случай, когда xz запускается сценарием или инструментом, например, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Сценарии могут использовать XZ_OPT, например, для установки специфических для сценария опций сжатия по умолчанию. Всё равно рекомендуется позволить пользователям переопределять XZ_OPT, если это разумно. Например, в сценариях sh(1) можно использовать что-то вроде этого: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY Синтаксис командной строки xz практически является надмножеством lzma, unlzma и lzcat из LZMA Utils 4.32.x. В большинстве случаев возможно заменить LZMA Utils на XZ Utils без нарушения существующих сценариев. Однако есть некоторые несовместимости, которые иногда могут вызвать проблемы. Уровни предустановок сжатия Нумерация предустановок уровней сжатия не идентична в xz и LZMA Utils. Самое важное различие - как размеры словарей сопоставляются с разными предустановками. Размер словаря примерно равен использованию памяти декомпрессором. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB Различия размеров словарей влияют на использование памяти компрессором тоже, но есть некоторые другие различия между LZMA Utils и XZ Utils, которые делают разницу ещё больше: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB Предустановленный уровень по умолчанию в LZMA Utils - -7, а в XZ Utils - -6, так что оба используют словарь 8 MiB по умолчанию. Потоковые vs. непотоковые файлы .lzma Размер распакованного файла может храниться в заголовке .lzma. LZMA Utils делает это при сжатии обычных файлов. Альтернатива - отметить, что размер распакованного файла неизвестен, и использовать маркер конца полезной нагрузки, чтобы указать, где декомпрессор должен остановиться. LZMA Utils использует этот метод, когда размер распакованного файла неизвестен, что является случаем, например, в конвейерах. xz поддерживает распаковку файлов .lzma с маркером конца полезной нагрузки или без него, но все файлы .lzma, созданные xz, будут использовать маркер конца полезной нагрузки и иметь размер распакованного файла, отмеченный как неизвестный в заголовке .lzma. Это может быть проблемой в некоторых необычных ситуациях. Например, декомпрессор .lzma в встраиваемом устройстве может работать только с файлами, у которых известен размер распакованного файла. Если вы столкнётесь с этой проблемой, вам нужно использовать LZMA Utils или LZMA SDK для создания файлов .lzma с известным размером распакованного файла. Неподдерживаемые файлы .lzma Формат .lzma позволяет значения lc до 8, а lp до 4. LZMA Utils может распаковывать файлы с любым lc и lp, но всегда создаёт файлы с lc=3 и lp=0. Создание файлов с другими lc и lp возможно с xz и с LZMA SDK. Реализация фильтра LZMA1 в liblzma требует, чтобы сумма lc и lp не превышала 4. Таким образом, файлы .lzma, которые превышают это ограничение, не могут быть распакованы с xz. LZMA Utils создаёт только файлы .lzma, у которых размер словаря - 2^n (степень двойки), но принимает файлы с любым размером словаря. liblzma принимает только файлы .lzma, у которых размер словаря - 2^n или 2^n + 2^(n-1). Это для уменьшения ложных срабатываний при обнаружении файлов .lzma. Эти ограничения не должны быть проблемой на практике, поскольку практически все файлы .lzma были сжаты с настройками, которые liblzma примет. Завершающий мусор При распаковке LZMA Utils молча игнорируют всё после первого потока .lzma. В большинстве ситуаций это ошибка. Это также означает, что LZMA Utils не поддерживают распаковку конкатенированных файлов .lzma. Если после первого потока .lzma остались данные, xz считает файл повреждённым, если не использовался --single-stream. Это может нарушить неясные сценарии, которые предполагали, что завершающий мусор игнорируется. NOTES Сжатый вывод может варьироваться Точный сжатый вывод, произведённый из одного и того же распакованного входного файла, может варьироваться между версиями XZ Utils, даже если опции сжатия идентичны. Это потому, что энкодер может быть улучшен (быстрее или лучше сжатие) без влияния на формат файла. Вывод может варьироваться даже между разными сборками одной и той же версии XZ Utils, если используются разные опции сборки. Вышеуказанное означает, что как только будет реализован --rsyncable, результирующие файлы не обязательно будут rsyncable, если старые и новые файлы были сжаты с одной версией xz. Эта проблема может быть исправлена, если часть реализации энкодера будет заморожена, чтобы сохранить rsyncable вывод стабильным между версиями xz. Встроенные декомпрессоры .xz Встроенные реализации декомпрессоров .xz, как XZ Embedded, не обязательно поддерживают файлы, созданные с типами проверок целостности, отличными от none и crc32. Поскольку значение по умолчанию - --check=crc64, вам нужно использовать --check=none или --check=crc32 при создании файлов для встроенных систем. За пределами встроенных систем все декомпрессоры формата .xz поддерживают все типы проверок, или, по крайней мере, способны распаковывать файл без проверки целостности, если конкретная проверка не поддерживается. XZ Embedded поддерживает фильтры BCJ, но только с смещением начала по умолчанию. EXAMPLES Основы Сжать файл foo в foo.xz с использованием уровня сжатия по умолчанию (-6) и удалить foo, если сжатие успешно: xz foo Распаковать bar.xz в bar и не удалять bar.xz, даже если распаковка успешна: xz -dk bar.xz Создать baz.tar.xz с предустановкой -4e (-4 --extreme), которая медленнее, чем значение по умолчанию -6, но требует меньше памяти для сжатия и распаковки (48 MiB и 5 MiB соответственно): tar cf - baz | xz -4e > baz.tar.xz Смесь сжатых и распакованных файлов может быть распакована в стандартный вывод с одной командой: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Параллельное сжатие многих файлов На GNU и *BSD find(1) и xargs(1) можно использовать для параллелизации сжатия многих файлов: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 Опция -P xargs(1) устанавливает количество параллельных процессов xz. Лучшее значение для опции -n зависит от того, сколько файлов нужно сжать. Если файлов всего несколько, значение, вероятно, должно быть 1; с десятками тысяч файлов 100 или даже больше может быть подходящим, чтобы уменьшить количество процессов xz, которые xargs(1) в конечном итоге создаст. Опция -T1 для xz указана, чтобы заставить его работать в однопоточном режиме, потому что xargs(1) используется для контроля количества параллелизации. Режим робота Вычислить, сколько байт было сэкономлено в сумме после сжатия нескольких файлов: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' Сценарий может захотеть знать, что он использует достаточно новую xz. Следующий сценарий sh(1) проверяет, что номер версии инструмента xz как минимум 5.0.0. Этот метод совместим со старыми бета-версиями, которые не поддерживали опцию --robot: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Пользовательские цепочки фильтров Самое простое использование пользовательских цепочек фильтров - настройка предустановки LZMA2. Это может быть полезно, потому что предустановки охватывают только подмножество потенциально полезных комбинаций настроек сжатия. Столбцы CompCPU таблиц из описаний опций -0 ... -9 и --extreme полезны при настройке предустановок LZMA2. Вот релевантные части, собранные из этих двух таблиц: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 Если вы знаете, что файл требует довольно большого словаря (например, 32 MiB), чтобы сжиматься хорошо, но вы хотите сжимать его быстрее, чем xz -8, предустановку с низким значением CompCPU (например, 1) можно изменить, чтобы использовать больший словарь: xz --lzma2=preset=1,dict=32MiB foo.tar С определёнными файлами указанная выше команда может быть быстрее, чем xz -6, при значительно лучшем сжатии. Однако стоит подчеркнуть, что только некоторые файлы受益 от большого словаря, сохраняя значение CompCPU низким. Наиболее очевидная ситуация, где большой словарь может помочь много, - архив, содержащий очень похожие файлы объёмом не менее нескольких мегабайт каждый. Размер словаря должен быть значительно больше, чем любой отдельный файл, чтобы позволить LZMA2 полностью использовать сходства между последовательными файлами. Если очень высокое использование памяти компрессором и декомпрессором допустимо, а файл, который сжимается, - не менее нескольких сотен мегабайт, может быть полезно использовать даже больший словарь, чем 64 MiB, который использует xz -9: xz -vv --lzma2=dict=192MiB big_foo.tar Использование -vv (--verbose --verbose), как в примере выше, может быть полезным, чтобы увидеть требования к памяти компрессора и декомпрессора. Помните, что использование словаря больше размера распакованного файла - трата памяти, так что указанная выше команда бесполезна для малых файлов. Иногда время сжатия не имеет значения, но использование памяти декомпрессором должно быть сохранено низким, например, чтобы сделать возможной распаковку файла на встраиваемой системе. Следующая команда использует -6e (-6 --extreme) как основу и устанавливает словарь только в 64 KiB. Получившийся файл можно распаковать с XZ Embedded (вот почему там --check=crc32), используя около 100 KiB памяти. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo Если вы хотите выжать как можно больше байт, корректировка количества битов контекста литералов (lc) и количества битов позиции (pb) иногда помогает. Корректировка количества битов позиции литералов (lp) может помочь тоже, но обычно lc и pb важнее. Например, архив исходного кода содержит в основном текст US-ASCII, так что что-то вроде следующего может дать немного (как 0.1%) меньший файл, чем xz -6e (попробуйте также без lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Использование другого фильтра вместе с LZMA2 может улучшить сжатие для определённых типов файлов. Например, чтобы сжать 32-битную или 64-битную разделяемую библиотеку x86 с фильтром BCJ x86: xz --x86 --lzma2 libfoo.so Обратите внимание, что порядок опций фильтров имеет значение. Если --x86 указан после --lzma2, xz выдаст ошибку, потому что после LZMA2 не может быть никаких фильтров, и также потому, что фильтр BCJ x86 не может быть использован как последний фильтр в цепочке. Фильтр Delta вместе с LZMA2 может дать хорошие результаты с растровыми изображениями. Он обычно должен превзойти PNG, который имеет несколько более продвинутых фильтров, чем простой дельта, но использует Deflate для фактического сжатия. Изображение должно быть сохранено в несжатом формате, например, как несжатый TIFF. Параметр расстояния фильтра Delta устанавливается для соответствия количеству байт на пиксель в изображении. Например, 24-битное растровое изображение RGB требует dist=3, и также хорошо передать pb=0 в LZMA2 для соответствия трёхбайтовому выравниванию: xz --delta=dist=3 --lzma2=pb=0 foo.tiff Если несколько изображений помещены в один архив (например, .tar), фильтр Delta будет работать и на этом, пока все изображения имеют одно и то же количество байт на пиксель. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html>
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Compress or decompress .xz and .lzma files SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz is equivalent to xz --decompress. xzcat is equivalent to xz --decompress --stdout. lzma is equivalent to xz --format=lzma. unlzma is equivalent to xz --format=lzma --decompress. lzcat is equivalent to xz --format=lzma --decompress --stdout. When writing scripts that need to decompress files, it is recommended to always use the name xz with appropriate arguments (xz -d or xz -dc) instead of the names unxz and xzcat. DESCRIPTION xz is a general-purpose data compression tool with command line syntax similar to gzip(1) and bzip2(1). The native file format is the .xz format, but the legacy .lzma format used by LZMA Utils and raw com‐ pressed streams with no container format headers are also supported. In addition, decompression of the .lz format used by lzip is supported. xz compresses or decompresses each file according to the selected oper‐ ation mode. If no files are given or file is -, xz reads from standard input and writes the processed data to standard output. xz will refuse (display an error and skip the file) to write compressed data to stan‐ dard output if it is a terminal. Similarly, xz will refuse to read compressed data from standard input if it is a terminal. Unless --stdout is specified, files other than - are written to a new file whose name is derived from the source file name: • When compressing, the suffix of the target file format (.xz or .lzma) is appended to the source filename to get the target file‐ name. • When decompressing, the .xz, .lzma, or .lz suffix is removed from the filename to get the target filename. xz also recognizes the suffixes .txz and .tlz, and replaces them with the .tar suffix. If the target file already exists, an error is displayed and the file is skipped. Unless writing to standard output, xz will display a warning and skip the file if any of the following applies: • File is not a regular file. Symbolic links are not followed, and thus they are not considered to be regular files. • File has more than one hard link. • File has setuid, setgid, or sticky bit set. • The operation mode is set to compress and the file already has a suffix of the target file format (.xz or .txz when compressing to the .xz format, and .lzma or .tlz when compressing to the .lzma for‐ mat). • The operation mode is set to decompress and the file doesn't have a suffix of any of the supported file formats (.xz, .txz, .lzma, .tlz, or .lz). After successfully compressing or decompressing the file, xz copies the owner, group, permissions, access time, and modification time from the source file to the target file. If copying the group fails, the per‐ missions are modified so that the target file doesn't become accessible to users who didn't have permission to access the source file. xz doesn't support copying other metadata like access control lists or ex‐ tended attributes yet. Once the target file has been successfully closed, the source file is removed unless --keep was specified. The source file is never removed if the output is written to standard output or if an error occurs. Sending SIGINFO or SIGUSR1 to the xz process makes it print progress information to standard error. This has only limited use since when standard error is a terminal, using --verbose will display an automati‐ cally updating progress indicator. Memory usage The memory usage of xz varies from a few hundred kilobytes to several gigabytes depending on the compression settings. The settings used when compressing a file determine the memory requirements of the decom‐ pressor. Typically the decompressor needs 5 % to 20 % of the amount of memory that the compressor needed when creating the file. For example, decompressing a file created with xz -9 currently requires 65 MiB of memory. Still, it is possible to have .xz files that require several gigabytes of memory to decompress. Especially users of older systems may find the possibility of very large memory usage annoying. To prevent uncomfortable surprises, xz has a built-in memory usage limiter, which is disabled by default. While some operating systems provide ways to limit the memory usage of processes, relying on it wasn't deemed to be flexible enough (for exam‐ ple, using ulimit(1) to limit virtual memory tends to cripple mmap(2)). The memory usage limiter can be enabled with the command line option --memlimit=limit. Often it is more convenient to enable the limiter by default by setting the environment variable XZ_DEFAULTS, for example, XZ_DEFAULTS=--memlimit=150MiB. It is possible to set the limits sepa‐ rately for compression and decompression by using --memlimit-com‐ press=limit and --memlimit-decompress=limit. Using these two options outside XZ_DEFAULTS is rarely useful because a single run of xz cannot do both compression and decompression and --memlimit=limit (or -M limit) is shorter to type on the command line. If the specified memory usage limit is exceeded when decompressing, xz will display an error and decompressing the file will fail. If the limit is exceeded when compressing, xz will try to scale the settings down so that the limit is no longer exceeded (except when using --for‐ mat=raw or --no-adjust). This way the operation won't fail unless the limit is very small. The scaling of the settings is done in steps that don't match the compression level presets, for example, if the limit is only slightly less than the amount required for xz -9, the settings will be scaled down only a little, not all the way down to xz -8. Concatenation and padding with .xz files It is possible to concatenate .xz files as is. xz will decompress such files as if they were a single .xz file. It is possible to insert padding between the concatenated parts or af‐ ter the last part. The padding must consist of null bytes and the size of the padding must be a multiple of four bytes. This can be useful, for example, if the .xz file is stored on a medium that measures file sizes in 512-byte blocks. Concatenation and padding are not allowed with .lzma files or raw streams. OPTIONS Integer suffixes and special values In most places where an integer argument is expected, an optional suf‐ fix is supported to easily indicate large integers. There must be no space between the integer and the suffix. KiB Multiply the integer by 1,024 (2^10). Ki, k, kB, K, and KB are accepted as synonyms for KiB. MiB Multiply the integer by 1,048,576 (2^20). Mi, m, M, and MB are accepted as synonyms for MiB. GiB Multiply the integer by 1,073,741,824 (2^30). Gi, g, G, and GB are accepted as synonyms for GiB. The special value max can be used to indicate the maximum integer value supported by the option. Operation mode If multiple operation mode options are given, the last one takes ef‐ fect. -z, --compress Compress. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, unxz implies --decompress). After successful compression, the source file is removed unless writing to standard output or --keep was specified. -d, --decompress, --uncompress Decompress. After successful decompression, the source file is removed unless writing to standard output or --keep was speci‐ fied. -t, --test Test the integrity of compressed files. This option is equiva‐ lent to --decompress --stdout except that the decompressed data is discarded instead of being written to standard output. No files are created or removed. -l, --list Print information about compressed files. No uncompressed out‐ put is produced, and no files are created or removed. In list mode, the program cannot read the compressed data from standard input or from other unseekable sources. The default listing shows basic information about files, one file per line. To get more detailed information, use also the --verbose option. For even more information, use --verbose twice, but note that this may be slow, because getting all the extra information requires many seeks. The width of verbose output exceeds 80 characters, so piping the output to, for exam‐ ple, less -S may be convenient if the terminal isn't wide enough. The exact output may vary between xz versions and different lo‐ cales. For machine-readable output, --robot --list should be used. Operation modifiers -k, --keep Don't delete the input files. Since xz 5.2.6, this option also makes xz compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. In earlier versions this was only done with --force. -f, --force This option has several effects: • If the target file already exists, delete it before compress‐ ing or decompressing. • Compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. • When used with --decompress --stdout and xz cannot recognize the type of the source file, copy the source file as is to standard output. This allows xzcat --force to be used like cat(1) for files that have not been compressed with xz. Note that in future, xz might support new compressed file formats, which may make xz decompress more types of files instead of copying them as is to standard output. --format=format can be used to restrict xz to decompress only a single file for‐ mat. -c, --stdout, --to-stdout Write the compressed or decompressed data to standard output in‐ stead of a file. This implies --keep. --single-stream Decompress only the first .xz stream, and silently ignore possi‐ ble remaining input data following the stream. Normally such trailing garbage makes xz display an error. xz never decompresses more than one stream from .lzma files or raw streams, but this option still makes xz ignore the possible trailing data after the .lzma file or raw stream. This option has no effect if the operation mode is not --decom‐ press or --test. --no-sparse Disable creation of sparse files. By default, if decompressing into a regular file, xz tries to make the file sparse if the de‐ compressed data contains long sequences of binary zeros. It also works when writing to standard output as long as standard output is connected to a regular file and certain additional conditions are met to make it safe. Creating sparse files may save disk space and speed up the decompression by reducing the amount of disk I/O. -S .suf, --suffix=.suf When compressing, use .suf as the suffix for the target file in‐ stead of .xz or .lzma. If not writing to standard output and the source file already has the suffix .suf, a warning is dis‐ played and the file is skipped. When decompressing, recognize files with the suffix .suf in ad‐ dition to files with the .xz, .txz, .lzma, .tlz, or .lz suffix. If the source file has the suffix .suf, the suffix is removed to get the target filename. When compressing or decompressing raw streams (--format=raw), the suffix must always be specified unless writing to standard output, because there is no default suffix for raw streams. --files[=file] Read the filenames to process from file; if file is omitted, filenames are read from standard input. Filenames must be ter‐ minated with the newline character. A dash (-) is taken as a regular filename; it doesn't mean standard input. If filenames are given also as command line arguments, they are processed be‐ fore the filenames read from file. --files0[=file] This is identical to --files[=file] except that each filename must be terminated with the null character. Basic file format and compression options -F format, --format=format Specify the file format to compress or decompress: auto This is the default. When compressing, auto is equiva‐ lent to xz. When decompressing, the format of the input file is automatically detected. Note that raw streams (created with --format=raw) cannot be auto-detected. xz Compress to the .xz file format, or accept only .xz files when decompressing. lzma, alone Compress to the legacy .lzma file format, or accept only .lzma files when decompressing. The alternative name alone is provided for backwards compatibility with LZMA Utils. lzip Accept only .lz files when decompressing. Compression is not supported. The .lz format version 0 and the unextended version 1 are supported. Version 0 files were produced by lzip 1.3 and older. Such files aren't common but may be found from file archives as a few source packages were released in this format. People might have old personal files in this format too. Decompression support for the format version 0 was removed in lzip 1.18. lzip 1.4 and later create files in the format version 1. The sync flush marker extension to the format version 1 was added in lzip 1.6. This extension is rarely used and isn't supported by xz (diagnosed as corrupt input). raw Compress or uncompress a raw stream (no headers). This is meant for advanced users only. To decode raw streams, you need use --format=raw and explicitly specify the fil‐ ter chain, which normally would have been stored in the container headers. -C check, --check=check Specify the type of the integrity check. The check is calcu‐ lated from the uncompressed data and stored in the .xz file. This option has an effect only when compressing into the .xz format; the .lzma format doesn't support integrity checks. The integrity check (if any) is verified when the .xz file is decom‐ pressed. Supported check types: none Don't calculate an integrity check at all. This is usu‐ ally a bad idea. This can be useful when integrity of the data is verified by other means anyway. crc32 Calculate CRC32 using the polynomial from IEEE-802.3 (Ethernet). crc64 Calculate CRC64 using the polynomial from ECMA-182. This is the default, since it is slightly better than CRC32 at detecting damaged files and the speed difference is neg‐ ligible. sha256 Calculate SHA-256. This is somewhat slower than CRC32 and CRC64. Integrity of the .xz headers is always verified with CRC32. It is not possible to change or disable it. --ignore-check Don't verify the integrity check of the compressed data when de‐ compressing. The CRC32 values in the .xz headers will still be verified normally. Do not use this option unless you know what you are doing. Pos‐ sible reasons to use this option: • Trying to recover data from a corrupt .xz file. • Speeding up decompression. This matters mostly with SHA-256 or with files that have compressed extremely well. It's rec‐ ommended to not use this option for this purpose unless the file integrity is verified externally in some other way. -0 ... -9 Select a compression preset level. The default is -6. If mul‐ tiple preset levels are specified, the last one takes effect. If a custom filter chain was already specified, setting a com‐ pression preset level clears the custom filter chain. The differences between the presets are more significant than with gzip(1) and bzip2(1). The selected compression settings determine the memory requirements of the decompressor, thus us‐ ing a too high preset level might make it painful to decompress the file on an old system with little RAM. Specifically, it's not a good idea to blindly use -9 for everything like it often is with gzip(1) and bzip2(1). -0 ... -3 These are somewhat fast presets. -0 is sometimes faster than gzip -9 while compressing much better. The higher ones often have speed comparable to bzip2(1) with compa‐ rable or better compression ratio, although the results depend a lot on the type of data being compressed. -4 ... -6 Good to very good compression while keeping decompressor memory usage reasonable even for old systems. -6 is the default, which is usually a good choice for distributing files that need to be decompressible even on systems with only 16 MiB RAM. (-5e or -6e may be worth considering too. See --extreme.) -7 ... -9 These are like -6 but with higher compressor and decom‐ pressor memory requirements. These are useful only when compressing files bigger than 8 MiB, 16 MiB, and 32 MiB, respectively. On the same hardware, the decompression speed is approximately a constant number of bytes of compressed data per second. In other words, the better the compression, the faster the decom‐ pression will usually be. This also means that the amount of uncompressed output produced per second can vary a lot. The following table summarises the features of the presets: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Column descriptions: • DictSize is the LZMA2 dictionary size. It is waste of memory to use a dictionary bigger than the size of the uncompressed file. This is why it is good to avoid using the presets -7 ... -9 when there's no real need for them. At -6 and lower, the amount of memory wasted is usually low enough to not mat‐ ter. • CompCPU is a simplified representation of the LZMA2 settings that affect compression speed. The dictionary size affects speed too, so while CompCPU is the same for levels -6 ... -9, higher levels still tend to be a little slower. To get even slower and thus possibly better compression, see --extreme. • CompMem contains the compressor memory requirements in the single-threaded mode. It may vary slightly between xz ver‐ sions. • DecMem contains the decompressor memory requirements. That is, the compression settings determine the memory require‐ ments of the decompressor. The exact decompressor memory us‐ age is slightly more than the LZMA2 dictionary size, but the values in the table have been rounded up to the next full MiB. Memory requirements of the multi-threaded mode are significantly higher than that of the single-threaded mode. With the default value of --block-size, each thread needs 3*3*DictSize plus Comp‐ Mem or DecMem. For example, four threads with preset -6 needs 660–670 MiB of memory. -e, --extreme Use a slower variant of the selected compression preset level (-0 ... -9) to hopefully get a little bit better compression ra‐ tio, but with bad luck this can also make it worse. Decompres‐ sor memory usage is not affected, but compressor memory usage increases a little at preset levels -0 ... -3. Since there are two presets with dictionary sizes 4 MiB and 8 MiB, the presets -3e and -5e use slightly faster settings (lower CompCPU) than -4e and -6e, respectively. That way no two presets are identical. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB For example, there are a total of four presets that use 8 MiB dictionary, whose order from the fastest to the slowest is -5, -6, -5e, and -6e. --fast --best These are somewhat misleading aliases for -0 and -9, respec‐ tively. These are provided only for backwards compatibility with LZMA Utils. Avoid using these options. --block-size=size When compressing to the .xz format, split the input data into blocks of size bytes. The blocks are compressed independently from each other, which helps with multi-threading and makes lim‐ ited random-access decompression possible. This option is typi‐ cally used to override the default block size in multi-threaded mode, but this option can be used in single-threaded mode too. In multi-threaded mode about three times size bytes will be al‐ located in each thread for buffering input and output. The de‐ fault size is three times the LZMA2 dictionary size or 1 MiB, whichever is more. Typically a good value is 2–4 times the size of the LZMA2 dictionary or at least 1 MiB. Using size less than the LZMA2 dictionary size is waste of RAM because then the LZMA2 dictionary buffer will never get fully used. In multi-threaded mode, the sizes of the blocks are stored in the block headers. This size information is required for multi-threaded decompres‐ sion. In single-threaded mode no block splitting is done by default. Setting this option doesn't affect memory usage. No size infor‐ mation is stored in block headers, thus files created in single- threaded mode won't be identical to files created in multi- threaded mode. The lack of size information also means that xz won't be able decompress the files in multi-threaded mode. --block-list=items When compressing to the .xz format, start a new block with an optional custom filter chain after the given intervals of uncom‐ pressed data. The items are a comma-separated list. Each item consists of an optional filter chain number between 0 and 9 followed by a colon (:) and a required size of uncompressed data. Omitting an item (two or more consecutive commas) is a shorthand to use the size and filters of the previous item. If the input file is bigger than the sum of the sizes in items, the last item is repeated until the end of the file. A special value of 0 may be used as the last size to indicate that the rest of the file should be encoded as a single block. An alternative filter chain for each block can be specified in combination with the --filters1=filters ... --filters9=filters options. These options define filter chains with an identifier between 1–9. Filter chain 0 can be used to refer to the default filter chain, which is the same as not specifying a filter chain. The filter chain identifier can be used before the un‐ compressed size, followed by a colon (:). For example, if one specifies --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB then blocks will be created using: • The filter chain specified by --filters1 and 2 MiB input • The filter chain specified by --filters3 and 2 MiB input • The filter chain specified by --filters2 and 4 MiB input • The filter chain specified by --filters2 and 4 MiB input • The default filter chain and 2 MiB input • The default filter chain and 4 MiB input for every block un‐ til end of input. If one specifies a size that exceeds the encoder's block size (either the default value in threaded mode or the value speci‐ fied with --block-size=size), the encoder will create additional blocks while keeping the boundaries specified in items. For ex‐ ample, if one specifies --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB and the input file is 80 MiB, one will get 11 blocks: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10, and 1 MiB. In multi-threaded mode the sizes of the blocks are stored in the block headers. This isn't done in single-threaded mode, so the encoded output won't be identical to that of the multi-threaded mode. --flush-timeout=timeout When compressing, if more than timeout milliseconds (a positive integer) has passed since the previous flush and reading more input would block, all the pending input data is flushed from the encoder and made available in the output stream. This can be useful if xz is used to compress data that is streamed over a network. Small timeout values make the data available at the receiving end with a small delay, but large timeout values give better compression ratio. This feature is disabled by default. If this option is speci‐ fied more than once, the last one takes effect. The special timeout value of 0 can be used to explicitly disable this fea‐ ture. This feature is not available on non-POSIX systems. This feature is still experimental. Currently xz is unsuitable for decompressing the stream in real time due to how xz does buffering. --memlimit-compress=limit Set a memory usage limit for compression. If this option is specified multiple times, the last one takes effect. If the compression settings exceed the limit, xz will attempt to adjust the settings downwards so that the limit is no longer ex‐ ceeded and display a notice that automatic adjustment was done. The adjustments are done in this order: reducing the number of threads, switching to single-threaded mode if even one thread in multi-threaded mode exceeds the limit, and finally reducing the LZMA2 dictionary size. When compressing with --format=raw or if --no-adjust has been specified, only the number of threads may be reduced since it can be done without affecting the compressed output. If the limit cannot be met even with the adjustments described above, an error is displayed and xz will exit with exit status 1. The limit can be specified in multiple ways: • The limit can be an absolute value in bytes. Using an inte‐ ger suffix like MiB can be useful. Example: --memlimit-com‐ press=80MiB • The limit can be specified as a percentage of total physical memory (RAM). This can be useful especially when setting the XZ_DEFAULTS environment variable in a shell initialization script that is shared between different computers. That way the limit is automatically bigger on systems with more mem‐ ory. Example: --memlimit-compress=70% • The limit can be reset back to its default value by setting it to 0. This is currently equivalent to setting the limit to max (no memory usage limit). For 32-bit xz there is a special case: if the limit would be over 4020 MiB, the limit is set to 4020 MiB. On MIPS32 2000 MiB is used instead. (The values 0 and max aren't affected by this. A similar feature doesn't exist for decompression.) This can be helpful when a 32-bit executable has access to 4 GiB address space (2 GiB on MIPS32) while hopefully doing no harm in other situations. See also the section Memory usage. --memlimit-decompress=limit Set a memory usage limit for decompression. This also affects the --list mode. If the operation is not possible without ex‐ ceeding the limit, xz will display an error and decompressing the file will fail. See --memlimit-compress=limit for possible ways to specify the limit. --memlimit-mt-decompress=limit Set a memory usage limit for multi-threaded decompression. This can only affect the number of threads; this will never make xz refuse to decompress a file. If limit is too low to allow any multi-threading, the limit is ignored and xz will continue in single-threaded mode. Note that if also --memlimit-decompress is used, it will always apply to both single-threaded and multi- threaded modes, and so the effective limit for multi-threading will never be higher than the limit set with --memlimit-decom‐ press. In contrast to the other memory usage limit options, --mem‐ limit-mt-decompress=limit has a system-specific default limit. xz --info-memory can be used to see the current value. This option and its default value exist because without any limit the threaded decompressor could end up allocating an in‐ sane amount of memory with some input files. If the default limit is too low on your system, feel free to increase the limit but never set it to a value larger than the amount of usable RAM as with appropriate input files xz will attempt to use that amount of memory even with a low number of threads. Running out of memory or swapping will not improve decompression perfor‐ mance. See --memlimit-compress=limit for possible ways to specify the limit. Setting limit to 0 resets the limit to the default sys‐ tem-specific value. -M limit, --memlimit=limit, --memory=limit This is equivalent to specifying --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Display an error and exit if the memory usage limit cannot be met without adjusting settings that affect the compressed out‐ put. That is, this prevents xz from switching the encoder from multi-threaded mode to single-threaded mode and from reducing the LZMA2 dictionary size. Even when this option is used the number of threads may be reduced to meet the memory usage limit as that won't affect the compressed output. Automatic adjusting is always disabled when creating raw streams (--format=raw). -T threads, --threads=threads Specify the number of worker threads to use. Setting threads to a special value 0 makes xz use up to as many threads as the pro‐ cessor(s) on the system support. The actual number of threads can be fewer than threads if the input file is not big enough for threading with the given settings or if using more threads would exceed the memory usage limit. The single-threaded and multi-threaded compressors produce dif‐ ferent output. Single-threaded compressor will give the small‐ est file size but only the output from the multi-threaded com‐ pressor can be decompressed using multiple threads. Setting threads to 1 will use the single-threaded mode. Setting threads to any other value, including 0, will use the multi-threaded compressor even if the system supports only one hardware thread. (xz 5.2.x used single-threaded mode in this situation.) To use multi-threaded mode with only one thread, set threads to +1. The + prefix has no effect with values other than 1. A memory usage limit can still make xz switch to single-threaded mode unless --no-adjust is used. Support for the + prefix was added in xz 5.4.0. If an automatic number of threads has been requested and no mem‐ ory usage limit has been specified, then a system-specific de‐ fault soft limit will be used to possibly limit the number of threads. It is a soft limit in sense that it is ignored if the number of threads becomes one, thus a soft limit will never stop xz from compressing or decompressing. This default soft limit will not make xz switch from multi-threaded mode to single- threaded mode. The active limits can be seen with xz --info-memory. Currently the only threading method is to split the input into blocks and compress them independently from each other. The de‐ fault block size depends on the compression level and can be overridden with the --block-size=size option. Threaded decompression only works on files that contain multiple blocks with size information in block headers. All large enough files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size has been used. The default value for threads is 0. In xz 5.4.x and older the default is 1. Custom compressor filter chains A custom filter chain allows specifying the compression settings in de‐ tail instead of relying on the settings associated to the presets. When a custom filter chain is specified, preset options (-0 ... -9 and --extreme) earlier on the command line are forgotten. If a preset op‐ tion is specified after one or more custom filter chain options, the new preset takes effect and the custom filter chain options specified earlier are forgotten. A filter chain is comparable to piping on the command line. When com‐ pressing, the uncompressed input goes to the first filter, whose output goes to the next filter (if any). The output of the last filter gets written to the compressed file. The maximum number of filters in the chain is four, but typically a filter chain has only one or two fil‐ ters. Many filters have limitations on where they can be in the filter chain: some filters can work only as the last filter in the chain, some only as a non-last filter, and some work in any position in the chain. De‐ pending on the filter, this limitation is either inherent to the filter design or exists to prevent security issues. A custom filter chain can be specified in two different ways. The op‐ tions --filters=filters and --filters1=filters ... --filters9=filters allow specifying an entire filter chain in one option using the liblzma filter string syntax. Alternatively, a filter chain can be specified by using one or more individual filter options in the order they are wanted in the filter chain. That is, the order of the individual fil‐ ter options is significant! When decoding raw streams (--format=raw), the filter chain must be specified in the same order as it was speci‐ fied when compressing. Any individual filter or preset options speci‐ fied before the full chain option (--filters=filters) will be forgot‐ ten. Individual filters specified after the full chain option will re‐ set the filter chain. Both the full and individual filter options take filter-specific op‐ tions as a comma-separated list. Extra commas in options are ignored. Every option has a default value, so specify those you want to change. To see the whole filter chain and options, use xz -vv (that is, use --verbose twice). This works also for viewing the filter chain options used by presets. --filters=filters Specify the full filter chain or a preset in a single option. Each filter can be separated by spaces or two dashes (--). fil‐ ters may need to be quoted on the shell command line so it is parsed as a single option. To denote options, use : or =. A preset can be prefixed with a - and followed with zero or more flags. The only supported flag is e to apply the same options as --extreme. --filters1=filters ... --filters9=filters Specify up to nine additional filter chains that can be used with --block-list. For example, when compressing an archive with executable files followed by text files, the executable part could use a filter chain with a BCJ filter and the text part only the LZMA2 filter. --filters-help Display a help message describing how to specify presets and custom filter chains in the --filters and --filters1=filters ... --filters9=filters options, and exit successfully. --lzma1[=options] --lzma2[=options] Add LZMA1 or LZMA2 filter to the filter chain. These filters can be used only as the last filter in the chain. LZMA1 is a legacy filter, which is supported almost solely due to the legacy .lzma file format, which supports only LZMA1. LZMA2 is an updated version of LZMA1 to fix some practical is‐ sues of LZMA1. The .xz format uses LZMA2 and doesn't support LZMA1 at all. Compression speed and ratios of LZMA1 and LZMA2 are practically the same. LZMA1 and LZMA2 share the same set of options: preset=preset Reset all LZMA1 or LZMA2 options to preset. Preset con‐ sist of an integer, which may be followed by single-let‐ ter preset modifiers. The integer can be from 0 to 9, matching the command line options -0 ... -9. The only supported modifier is currently e, which matches --ex‐ treme. If no preset is specified, the default values of LZMA1 or LZMA2 options are taken from the preset 6. dict=size Dictionary (history buffer) size indicates how many bytes of the recently processed uncompressed data is kept in memory. The algorithm tries to find repeating byte se‐ quences (matches) in the uncompressed data, and replace them with references to the data currently in the dictio‐ nary. The bigger the dictionary, the higher is the chance to find a match. Thus, increasing dictionary size usually improves compression ratio, but a dictionary big‐ ger than the uncompressed file is waste of memory. Typical dictionary size is from 64 KiB to 64 MiB. The minimum is 4 KiB. The maximum for compression is cur‐ rently 1.5 GiB (1536 MiB). The decompressor already sup‐ ports dictionaries up to one byte less than 4 GiB, which is the maximum for the LZMA1 and LZMA2 stream formats. Dictionary size and match finder (mf) together determine the memory usage of the LZMA1 or LZMA2 encoder. The same (or bigger) dictionary size is required for decompressing that was used when compressing, thus the memory usage of the decoder is determined by the dictionary size used when compressing. The .xz headers store the dictionary size either as 2^n or 2^n + 2^(n-1), so these sizes are somewhat preferred for compression. Other sizes will get rounded up when stored in the .xz headers. lc=lc Specify the number of literal context bits. The minimum is 0 and the maximum is 4; the default is 3. In addi‐ tion, the sum of lc and lp must not exceed 4. All bytes that cannot be encoded as matches are encoded as literals. That is, literals are simply 8-bit bytes that are encoded one at a time. The literal coding makes an assumption that the highest lc bits of the previous uncompressed byte correlate with the next byte. For example, in typical English text, an upper-case letter is often followed by a lower-case let‐ ter, and a lower-case letter is usually followed by an‐ other lower-case letter. In the US-ASCII character set, the highest three bits are 010 for upper-case letters and 011 for lower-case letters. When lc is at least 3, the literal coding can take advantage of this property in the uncompressed data. The default value (3) is usually good. If you want maxi‐ mum compression, test lc=4. Sometimes it helps a little, and sometimes it makes compression worse. If it makes it worse, test lc=2 too. lp=lp Specify the number of literal position bits. The minimum is 0 and the maximum is 4; the default is 0. Lp affects what kind of alignment in the uncompressed data is assumed when encoding literals. See pb below for more information about alignment. pb=pb Specify the number of position bits. The minimum is 0 and the maximum is 4; the default is 2. Pb affects what kind of alignment in the uncompressed data is assumed in general. The default means four-byte alignment (2^pb=2^2=4), which is often a good choice when there's no better guess. When the alignment is known, setting pb accordingly may reduce the file size a little. For example, with text files having one-byte alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can improve compression slightly. For UTF-16 text, pb=1 is a good choice. If the alignment is an odd number like 3 bytes, pb=0 might be the best choice. Even though the assumed alignment can be adjusted with pb and lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment. It might be worth taking into account when designing file formats that are likely to be often com‐ pressed with LZMA1 or LZMA2. mf=mf Match finder has a major effect on encoder speed, memory usage, and compression ratio. Usually Hash Chain match finders are faster than Binary Tree match finders. The default depends on the preset: 0 uses hc3, 1–3 use hc4, and the rest use bt4. The following match finders are supported. The memory usage formulas below are rough approximations, which are closest to the reality when dict is a power of two. hc3 Hash Chain with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 7.5 (if dict <= 16 MiB); dict * 5.5 + 64 MiB (if dict > 16 MiB) hc4 Hash Chain with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 7.5 (if dict <= 32 MiB); dict * 6.5 (if dict > 32 MiB) bt2 Binary Tree with 2-byte hashing Minimum value for nice: 2 Memory usage: dict * 9.5 bt3 Binary Tree with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 11.5 (if dict <= 16 MiB); dict * 9.5 + 64 MiB (if dict > 16 MiB) bt4 Binary Tree with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 11.5 (if dict <= 32 MiB); dict * 10.5 (if dict > 32 MiB) mode=mode Compression mode specifies the method to analyze the data produced by the match finder. Supported modes are fast and normal. The default is fast for presets 0–3 and nor‐ mal for presets 4–9. Usually fast is used with Hash Chain match finders and normal with Binary Tree match finders. This is also what the presets do. nice=nice Specify what is considered to be a nice length for a match. Once a match of at least nice bytes is found, the algorithm stops looking for possibly better matches. Nice can be 2–273 bytes. Higher values tend to give bet‐ ter compression ratio at the expense of speed. The de‐ fault depends on the preset. depth=depth Specify the maximum search depth in the match finder. The default is the special value of 0, which makes the compressor determine a reasonable depth from mf and nice. Reasonable depth for Hash Chains is 4–100 and 16–1000 for Binary Trees. Using very high values for depth can make the encoder extremely slow with some files. Avoid set‐ ting the depth over 1000 unless you are prepared to in‐ terrupt the compression in case it is taking far too long. When decoding raw streams (--format=raw), LZMA2 needs only the dictionary size. LZMA1 needs also lc, lp, and pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Add a branch/call/jump (BCJ) filter to the filter chain. These filters can be used only as a non-last filter in the filter chain. A BCJ filter converts relative addresses in the machine code to their absolute counterparts. This doesn't change the size of the data but it increases redundancy, which can help LZMA2 to produce 0–15 % smaller .xz file. The BCJ filters are always re‐ versible, so using a BCJ filter for wrong type of data doesn't cause any data loss, although it may make the compression ratio slightly worse. The BCJ filters are very fast and use an in‐ significant amount of memory. These BCJ filters have known problems related to the compression ratio: • Some types of files containing executable code (for example, object files, static libraries, and Linux kernel modules) have the addresses in the instructions filled with filler values. These BCJ filters will still do the address conver‐ sion, which will make the compression worse with these files. • If a BCJ filter is applied on an archive, it is possible that it makes the compression ratio worse than not using a BCJ filter. For example, if there are similar or even identical executables then filtering will likely make the files less similar and thus compression is worse. The contents of non- executable files in the same archive can matter too. In practice one has to try with and without a BCJ filter to see which is better in each situation. Different instruction sets have different alignment: the exe‐ cutable file must be aligned to a multiple of this value in the input data to make the filter work. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit or 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Since the BCJ-filtered data is usually compressed with LZMA2, the compression ratio may be improved slightly if the LZMA2 op‐ tions are set to match the alignment of the selected BCJ filter. Examples: • IA-64 filter has 16-byte alignment so pb=4,lp=4,lc=0 is good with LZMA2 (2^4=16). • RISC-V code has 2-byte or 4-byte alignment depending on whether the file contains 16-bit compressed instructions (the C extension). When 16-bit instructions are used, pb=2,lp=1,lc=3 or pb=1,lp=1,lc=3 is good. When 16-bit in‐ structions aren't present, pb=2,lp=2,lc=2 is the best. read‐ elf -h can be used to check if "RVC" appears on the "Flags" line. • ARM64 is always 4-byte aligned so pb=2,lp=2,lc=2 is the best. • The x86 filter is an exception. It's usually good to stick to LZMA2's defaults (pb=2,lp=0,lc=3) when compressing x86 ex‐ ecutables. All BCJ filters support the same options: start=offset Specify the start offset that is used when converting be‐ tween relative and absolute addresses. The offset must be a multiple of the alignment of the filter (see the ta‐ ble above). The default is zero. In practice, the de‐ fault is good; specifying a custom offset is almost never useful. --delta[=options] Add the Delta filter to the filter chain. The Delta filter can be only used as a non-last filter in the filter chain. Currently only simple byte-wise delta calculation is supported. It can be useful when compressing, for example, uncompressed bitmap images or uncompressed PCM audio. However, special pur‐ pose algorithms may give significantly better results than Delta + LZMA2. This is true especially with audio, which compresses faster and better, for example, with flac(1). Supported options: dist=distance Specify the distance of the delta calculation in bytes. distance must be 1–256. The default is 1. For example, with dist=2 and eight-byte input A1 B1 A2 B3 A3 B5 A4 B7, the output will be A1 B1 01 02 01 02 01 02. Other options -q, --quiet Suppress warnings and notices. Specify this twice to suppress errors too. This option has no effect on the exit status. That is, even if a warning was suppressed, the exit status to indi‐ cate a warning is still used. -v, --verbose Be verbose. If standard error is connected to a terminal, xz will display a progress indicator. Specifying --verbose twice will give even more verbose output. The progress indicator shows the following information: • Completion percentage is shown if the size of the input file is known. That is, the percentage cannot be shown in pipes. • Amount of compressed data produced (compressing) or consumed (decompressing). • Amount of uncompressed data consumed (compressing) or pro‐ duced (decompressing). • Compression ratio, which is calculated by dividing the amount of compressed data processed so far by the amount of uncom‐ pressed data processed so far. • Compression or decompression speed. This is measured as the amount of uncompressed data consumed (compression) or pro‐ duced (decompression) per second. It is shown after a few seconds have passed since xz started processing the file. • Elapsed time in the format M:SS or H:MM:SS. • Estimated remaining time is shown only when the size of the input file is known and a couple of seconds have already passed since xz started processing the file. The time is shown in a less precise format which never has any colons, for example, 2 min 30 s. When standard error is not a terminal, --verbose will make xz print the filename, compressed size, uncompressed size, compres‐ sion ratio, and possibly also the speed and elapsed time on a single line to standard error after compressing or decompressing the file. The speed and elapsed time are included only when the operation took at least a few seconds. If the operation didn't finish, for example, due to user interruption, also the comple‐ tion percentage is printed if the size of the input file is known. -Q, --no-warn Don't set the exit status to 2 even if a condition worth a warn‐ ing was detected. This option doesn't affect the verbosity level, thus both --quiet and --no-warn have to be used to not display warnings and to not alter the exit status. --robot Print messages in a machine-parsable format. This is intended to ease writing frontends that want to use xz instead of li‐ blzma, which may be the case with various scripts. The output with this option enabled is meant to be stable across xz re‐ leases. See the section ROBOT MODE for details. --info-memory Display, in human-readable format, how much physical memory (RAM) and how many processor threads xz thinks the system has and the memory usage limits for compression and decompression, and exit successfully. -h, --help Display a help message describing the most commonly used op‐ tions, and exit successfully. -H, --long-help Display a help message describing all features of xz, and exit successfully -V, --version Display the version number of xz and liblzma in human readable format. To get machine-parsable output, specify --robot before --version. ROBOT MODE The robot mode is activated with the --robot option. It makes the out‐ put of xz easier to parse by other programs. Currently --robot is sup‐ ported only together with --list, --filters-help, --info-memory, and --version. It will be supported for compression and decompression in the future. List mode xz --robot --list uses tab-separated output. The first column of every line has a string that indicates the type of the information found on that line: name This is always the first line when starting to list a file. The second column on the line is the filename. file This line contains overall information about the .xz file. This line is always printed after the name line. stream This line type is used only when --verbose was specified. There are as many stream lines as there are streams in the .xz file. block This line type is used only when --verbose was specified. There are as many block lines as there are blocks in the .xz file. The block lines are shown after all the stream lines; different line types are not interleaved. summary This line type is used only when --verbose was specified twice. This line is printed after all block lines. Like the file line, the summary line contains overall information about the .xz file. totals This line is always the very last line of the list output. It shows the total counts and sizes. The columns of the file lines: 2. Number of streams in the file 3. Total number of blocks in the stream(s) 4. Compressed size of the file 5. Uncompressed size of the file 6. Compression ratio, for example, 0.123. If ratio is over 9.999, three dashes (---) are displayed instead of the ra‐ tio. 7. Comma-separated list of integrity check names. The follow‐ ing strings are used for the known check types: None, CRC32, CRC64, and SHA-256. For unknown check types, Unknown-N is used, where N is the Check ID as a decimal number (one or two digits). 8. Total size of stream padding in the file The columns of the stream lines: 2. Stream number (the first stream is 1) 3. Number of blocks in the stream 4. Compressed start offset 5. Uncompressed start offset 6. Compressed size (does not include stream padding) 7. Uncompressed size 8. Compression ratio 9. Name of the integrity check 10. Size of stream padding The columns of the block lines: 2. Number of the stream containing this block 3. Block number relative to the beginning of the stream (the first block is 1) 4. Block number relative to the beginning of the file 5. Compressed start offset relative to the beginning of the file 6. Uncompressed start offset relative to the beginning of the file 7. Total compressed size of the block (includes headers) 8. Uncompressed size 9. Compression ratio 10. Name of the integrity check If --verbose was specified twice, additional columns are included on the block lines. These are not displayed with a single --verbose, be‐ cause getting this information requires many seeks and can thus be slow: 11. Value of the integrity check in hexadecimal 12. Block header size 13. Block flags: c indicates that compressed size is present, and u indicates that uncompressed size is present. If the flag is not set, a dash (-) is shown instead to keep the string length fixed. New flags may be added to the end of the string in the future. 14. Size of the actual compressed data in the block (this ex‐ cludes the block header, block padding, and check fields) 15. Amount of memory (in bytes) required to decompress this block with this xz version 16. Filter chain. Note that most of the options used at com‐ pression time cannot be known, because only the options that are needed for decompression are stored in the .xz headers. The columns of the summary lines: 2. Amount of memory (in bytes) required to decompress this file with this xz version 3. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 4. Minimum xz version required to decompress the file The columns of the totals line: 2. Number of streams 3. Number of blocks 4. Compressed size 5. Uncompressed size 6. Average compression ratio 7. Comma-separated list of integrity check names that were present in the files 8. Stream padding size 9. Number of files. This is here to keep the order of the ear‐ lier columns the same as on file lines. If --verbose was specified twice, additional columns are included on the totals line: 10. Maximum amount of memory (in bytes) required to decompress the files with this xz version 11. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 12. Minimum xz version required to decompress the file Future versions may add new line types and new columns can be added to the existing line types, but the existing columns won't be changed. Filters help xz --robot --filters-help prints the supported filters in the following format: filter:option=<value>,option=<value>... filter Name of the filter option Name of a filter specific option value Numeric value ranges appear as <min-max>. String value choices are shown within < > and separated by a | character. Each filter is printed on its own line. Memory limit information xz --robot --info-memory prints a single line with multiple tab-sepa‐ rated columns: 1. Total amount of physical memory (RAM) in bytes. 2. Memory usage limit for compression in bytes (--memlimit-compress). A special value of 0 indicates the default setting which for sin‐ gle-threaded mode is the same as no limit. 3. Memory usage limit for decompression in bytes (--memlimit-decom‐ press). A special value of 0 indicates the default setting which for single-threaded mode is the same as no limit. 4. Since xz 5.3.4alpha: Memory usage for multi-threaded decompression in bytes (--memlimit-mt-decompress). This is never zero because a system-specific default value shown in the column 5 is used if no limit has been specified explicitly. This is also never greater than the value in the column 3 even if a larger value has been specified with --memlimit-mt-decompress. 5. Since xz 5.3.4alpha: A system-specific default memory usage limit that is used to limit the number of threads when compressing with an automatic number of threads (--threads=0) and no memory usage limit has been specified (--memlimit-compress). This is also used as the default value for --memlimit-mt-decompress. 6. Since xz 5.3.4alpha: Number of available processor threads. In the future, the output of xz --robot --info-memory may have more columns, but never more than a single line. Version xz --robot --version prints the version number of xz and liblzma in the following format: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Major version. YYY Minor version. Even numbers are stable. Odd numbers are alpha or beta versions. ZZZ Patch level for stable releases or just a counter for develop‐ ment releases. S Stability. 0 is alpha, 1 is beta, and 2 is stable. S should be always 2 when YYY is even. XYYYZZZS are the same on both lines if xz and liblzma are from the same XZ Utils release. Examples: 4.999.9beta is 49990091 and 5.0.0 is 50000002. EXIT STATUS 0 All is good. 1 An error occurred. 2 Something worth a warning occurred, but no actual errors oc‐ curred. Notices (not warnings or errors) printed on standard error don't affect the exit status. ENVIRONMENT xz parses space-separated lists of options from the environment vari‐ ables XZ_DEFAULTS and XZ_OPT, in this order, before parsing the options from the command line. Note that only options are parsed from the en‐ vironment variables; all non-options are silently ignored. Parsing is done with getopt_long(3) which is used also for the command line argu‐ ments. XZ_DEFAULTS User-specific or system-wide default options. Typically this is set in a shell initialization script to enable xz's memory usage limiter by default. Excluding shell initialization scripts and similar special cases, scripts must never set or unset XZ_DE‐ FAULTS. XZ_OPT This is for passing options to xz when it is not possible to set the options directly on the xz command line. This is the case when xz is run by a script or tool, for example, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Scripts may use XZ_OPT, for example, to set script-specific de‐ fault compression options. It is still recommended to allow users to override XZ_OPT if that is reasonable. For example, in sh(1) scripts one may use something like this: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY The command line syntax of xz is practically a superset of lzma, un‐ lzma, and lzcat as found from LZMA Utils 4.32.x. In most cases, it is possible to replace LZMA Utils with XZ Utils without breaking existing scripts. There are some incompatibilities though, which may sometimes cause problems. Compression preset levels The numbering of the compression level presets is not identical in xz and LZMA Utils. The most important difference is how dictionary sizes are mapped to different presets. Dictionary size is roughly equal to the decompressor memory usage. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB The dictionary size differences affect the compressor memory usage too, but there are some other differences between LZMA Utils and XZ Utils, which make the difference even bigger: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB The default preset level in LZMA Utils is -7 while in XZ Utils it is -6, so both use an 8 MiB dictionary by default. Streamed vs. non-streamed .lzma files The uncompressed size of the file can be stored in the .lzma header. LZMA Utils does that when compressing regular files. The alternative is to mark that uncompressed size is unknown and use end-of-payload marker to indicate where the decompressor should stop. LZMA Utils uses this method when uncompressed size isn't known, which is the case, for example, in pipes. xz supports decompressing .lzma files with or without end-of-payload marker, but all .lzma files created by xz will use end-of-payload marker and have uncompressed size marked as unknown in the .lzma header. This may be a problem in some uncommon situations. For exam‐ ple, a .lzma decompressor in an embedded device might work only with files that have known uncompressed size. If you hit this problem, you need to use LZMA Utils or LZMA SDK to create .lzma files with known un‐ compressed size. Unsupported .lzma files The .lzma format allows lc values up to 8, and lp values up to 4. LZMA Utils can decompress files with any lc and lp, but always creates files with lc=3 and lp=0. Creating files with other lc and lp is possible with xz and with LZMA SDK. The implementation of the LZMA1 filter in liblzma requires that the sum of lc and lp must not exceed 4. Thus, .lzma files, which exceed this limitation, cannot be decompressed with xz. LZMA Utils creates only .lzma files which have a dictionary size of 2^n (a power of 2) but accepts files with any dictionary size. liblzma ac‐ cepts only .lzma files which have a dictionary size of 2^n or 2^n + 2^(n-1). This is to decrease false positives when detecting .lzma files. These limitations shouldn't be a problem in practice, since practically all .lzma files have been compressed with settings that liblzma will accept. Trailing garbage When decompressing, LZMA Utils silently ignore everything after the first .lzma stream. In most situations, this is a bug. This also means that LZMA Utils don't support decompressing concatenated .lzma files. If there is data left after the first .lzma stream, xz considers the file to be corrupt unless --single-stream was used. This may break ob‐ scure scripts which have assumed that trailing garbage is ignored. NOTES Compressed output may vary The exact compressed output produced from the same uncompressed input file may vary between XZ Utils versions even if compression options are identical. This is because the encoder can be improved (faster or bet‐ ter compression) without affecting the file format. The output can vary even between different builds of the same XZ Utils version, if different build options are used. The above means that once --rsyncable has been implemented, the result‐ ing files won't necessarily be rsyncable unless both old and new files have been compressed with the same xz version. This problem can be fixed if a part of the encoder implementation is frozen to keep rsynca‐ ble output stable across xz versions. Embedded .xz decompressors Embedded .xz decompressor implementations like XZ Embedded don't neces‐ sarily support files created with integrity check types other than none and crc32. Since the default is --check=crc64, you must use --check=none or --check=crc32 when creating files for embedded systems. Outside embedded systems, all .xz format decompressors support all the check types, or at least are able to decompress the file without veri‐ fying the integrity check if the particular check is not supported. XZ Embedded supports BCJ filters, but only with the default start off‐ set. EXAMPLES Basics Compress the file foo into foo.xz using the default compression level (-6), and remove foo if compression is successful: xz foo Decompress bar.xz into bar and don't remove bar.xz even if decompres‐ sion is successful: xz -dk bar.xz Create baz.tar.xz with the preset -4e (-4 --extreme), which is slower than the default -6, but needs less memory for compression and decom‐ pression (48 MiB and 5 MiB, respectively): tar cf - baz | xz -4e > baz.tar.xz A mix of compressed and uncompressed files can be decompressed to stan‐ dard output with a single command: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Parallel compression of many files On GNU and *BSD, find(1) and xargs(1) can be used to parallelize com‐ pression of many files: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 The -P option to xargs(1) sets the number of parallel xz processes. The best value for the -n option depends on how many files there are to be compressed. If there are only a couple of files, the value should probably be 1; with tens of thousands of files, 100 or even more may be appropriate to reduce the number of xz processes that xargs(1) will eventually create. The option -T1 for xz is there to force it to single-threaded mode, be‐ cause xargs(1) is used to control the amount of parallelization. Robot mode Calculate how many bytes have been saved in total after compressing multiple files: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' A script may want to know that it is using new enough xz. The follow‐ ing sh(1) script checks that the version number of the xz tool is at least 5.0.0. This method is compatible with old beta versions, which didn't support the --robot option: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Set a memory usage limit for decompression using XZ_OPT, but if a limit has already been set, don't increase it: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Custom compressor filter chains The simplest use for custom filter chains is customizing a LZMA2 pre‐ set. This can be useful, because the presets cover only a subset of the potentially useful combinations of compression settings. The CompCPU columns of the tables from the descriptions of the options -0 ... -9 and --extreme are useful when customizing LZMA2 presets. Here are the relevant parts collected from those two tables: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 If you know that a file requires somewhat big dictionary (for example, 32 MiB) to compress well, but you want to compress it quicker than xz -8 would do, a preset with a low CompCPU value (for example, 1) can be modified to use a bigger dictionary: xz --lzma2=preset=1,dict=32MiB foo.tar With certain files, the above command may be faster than xz -6 while compressing significantly better. However, it must be emphasized that only some files benefit from a big dictionary while keeping the CompCPU value low. The most obvious situation, where a big dictionary can help a lot, is an archive containing very similar files of at least a few megabytes each. The dictionary size has to be significantly bigger than any individual file to allow LZMA2 to take full advantage of the similarities between consecutive files. If very high compressor and decompressor memory usage is fine, and the file being compressed is at least several hundred megabytes, it may be useful to use an even bigger dictionary than the 64 MiB that xz -9 would use: xz -vv --lzma2=dict=192MiB big_foo.tar Using -vv (--verbose --verbose) like in the above example can be useful to see the memory requirements of the compressor and decompressor. Re‐ member that using a dictionary bigger than the size of the uncompressed file is waste of memory, so the above command isn't useful for small files. Sometimes the compression time doesn't matter, but the decompressor memory usage has to be kept low, for example, to make it possible to decompress the file on an embedded system. The following command uses -6e (-6 --extreme) as a base and sets the dictionary to only 64 KiB. The resulting file can be decompressed with XZ Embedded (that's why there is --check=crc32) using about 100 KiB of memory. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo If you want to squeeze out as many bytes as possible, adjusting the number of literal context bits (lc) and number of position bits (pb) can sometimes help. Adjusting the number of literal position bits (lp) might help too, but usually lc and pb are more important. For example, a source code archive contains mostly US-ASCII text, so something like the following might give slightly (like 0.1 %) smaller file than xz -6e (try also without lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Using another filter together with LZMA2 can improve compression with certain file types. For example, to compress a x86-32 or x86-64 shared library using the x86 BCJ filter: xz --x86 --lzma2 libfoo.so Note that the order of the filter options is significant. If --x86 is specified after --lzma2, xz will give an error, because there cannot be any filter after LZMA2, and also because the x86 BCJ filter cannot be used as the last filter in the chain. The Delta filter together with LZMA2 can give good results with bitmap images. It should usually beat PNG, which has a few more advanced fil‐ ters than simple delta but uses Deflate for the actual compression. The image has to be saved in uncompressed format, for example, as un‐ compressed TIFF. The distance parameter of the Delta filter is set to match the number of bytes per pixel in the image. For example, 24-bit RGB bitmap needs dist=3, and it is also good to pass pb=0 to LZMA2 to accommodate the three-byte alignment: xz --delta=dist=3 --lzma2=pb=0 foo.tiff If multiple images have been put into a single archive (for example, .tar), the Delta filter will work on that too as long as all images have the same number of bytes per pixel. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html> Tukaani 2024-12-30 XZ(1)
LZMAINFO(1) XZ Utils LZMAINFO(1) NAME lzmainfo - отображение информации, хранящейся в заголовке файла .lzma SYNOPSIS lzmainfo [--help] [--version] [file...] DESCRIPTION lzmainfo отображает информацию, хранящуюся в заголовке файла .lzma. Он читает первые 13 байтов из указанного файла, декодирует заголовок и выводит его в стандартный вывод в удобочитаемом формате. Если файлы не указаны или файл равен -, читается стандартный ввод. Обычно самая интересная информация - это размер несжатых данных и размер словаря. Размер несжатых данных можно отобразить только если файл в варианте формата .lzma без потоковой передачи. Количество памяти, необходимое для распаковки файла, составляет несколько десятков килобайт плюс размер словаря. lzmainfo включен в XZ Utils в первую очередь для обеспечения обратной совместимости с LZMA Utils. EXIT STATUS 0 Всё в порядке. 1 Произошла ошибка. BUGS lzmainfo использует MB, в то время как правильный суффикс - MiB (2^20 байт). Это для сохранения совместимости вывода с LZMA Utils. SEE ALSO xz(1) Tukaani 2013-06-30 LZMAINFO(1)
LZMAINFO(1) XZ Utils LZMAINFO(1) NAME lzmainfo - show information stored in the .lzma file header SYNOPSIS lzmainfo [--help] [--version] [file...] DESCRIPTION lzmainfo shows information stored in the .lzma file header. It reads the first 13 bytes from the specified file, decodes the header, and prints it to standard output in human readable format. If no files are given or file is -, standard input is read. Usually the most interesting information is the uncompressed size and the dictionary size. Uncompressed size can be shown only if the file is in the non-streamed .lzma format variant. The amount of memory re‐ quired to decompress the file is a few dozen kilobytes plus the dictio‐ nary size. lzmainfo is included in XZ Utils primarily for backward compatibility with LZMA Utils. EXIT STATUS 0 All is good. 1 An error occurred. BUGS lzmainfo uses MB while the correct suffix would be MiB (2^20 bytes). This is to keep the output compatible with LZMA Utils. SEE ALSO xz(1) Tukaani 2013-06-30 LZMAINFO(1)
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Сжатие или распаковка файлов .xz и .lzma SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz эквивалентно xz --decompress. xzcat эквивалентно xz --decompress --stdout. lzma эквивалентно xz --format=lzma. unlzma эквивалентно xz --format=lzma --decompress. lzcat эквивалентно xz --format=lzma --decompress --stdout. При написании скриптов, которые нуждаются в распаковке файлов, рекомендуется всегда использовать имя xz с подходящими аргументами (xz -d или xz -dc) вместо имён unxz и xzcat. DESCRIPTION xz - это универсальный инструмент сжатия данных с синтаксисом командной строки, похожим на gzip(1) и bzip2(1). Родной формат файлов - это формат .xz, но также поддерживается устаревший формат .lzma, используемый в LZMA Utils, и необработанные сжатые потоки без заголовков контейнера. Кроме того, поддерживается распаковка формата .lz, используемого lzip. xz сжимает или распаковывает каждый файл в соответствии с выбранным режимом операции. Если файлы не указаны или файл - это -, xz читает из стандартного ввода и записывает обработанные данные в стандартный вывод. xz откажется (выдаст ошибку и пропустит файл) записывать сжатые данные в стандартный вывод, если это терминал. Аналогично, xz откажется читать сжатые данные из стандартного ввода, если это терминал. Если --stdout не указан, файлы, отличные от -, записываются в новый файл, имя которого выводится из имени исходного файла: • При сжатии, суффикс целевого формата файла (.xz или .lzma) добавляется к имени исходного файла для получения имени целевого файла. • При распаковке, суффикс .xz, .lzma или .lz удаляется из имени файла, чтобы получить имя целевого файла. xz также распознаёт суффиксы .txz и .tlz и заменяет их на суффикс .tar. Если целевой файл уже существует, выводится ошибка и файл пропускается. Если не запись в стандартный вывод, xz выведет предупреждение и пропустит файл, если выполняется любое из следующих условий: • Файл не является обычным файлом. Символические ссылки не следуются и, следовательно, не считаются обычными файлами. • Файл имеет более одной жёсткой ссылки. • Файл имеет установленными биты setuid, setgid или sticky. • Режим операции установлен на сжатие и файл уже имеет суффикс целевого формата файла (.xz или .txz при сжатии в формат .xz, и .lzma или .tlz при сжатии в формат .lzma). • Режим операции установлен на распаковку и файл не имеет суффикса какого-либо из поддерживаемых форматов файлов (.xz, .txz, .lzma, .tlz или .lz). После успешного сжатия или распаковки файла xz копирует владельца, группу, права доступа, время доступа и время изменения из исходного файла в целевой файл. Если копирование группы не удаётся, права доступа изменяются так, чтобы целевой файл не стал доступным для пользователей, у которых не было доступа к исходному файлу. xz пока не поддерживает копирование другой метаданных, такой как списки контроля доступа или расширенные атрибуты. После успешного закрытия целевого файла исходный файл удаляется, если не указан --keep. Исходный файл никогда не удаляется, если вывод записывается в стандартный вывод или если возникает ошибка. Отправка SIGINFO или SIGUSR1 процессу xz заставляет его выводить информацию о прогрессе в стандартный вывод ошибок. Это имеет ограниченное применение, поскольку, если стандартный вывод ошибок является терминалом, использование --verbose отобразит автоматически обновляемый индикатор прогресса. Использование памяти Использование памяти xz варьируется от нескольких сотен килобайт до нескольких гигабайт в зависимости от настроек сжатия. Настройки, используемые при сжатии файла, определяют требования к памяти декомпрессора. Обычно декомпрессору требуется 5 % до 20 % от объёма памяти, необходимого компрессору при создании файла. Например, распаковка файла, созданного с помощью xz -9, в настоящее время требует 65 MiB памяти. Тем не менее, возможно, иметь файлы .xz, требующие нескольких гигабайт памяти для распаковки. Особенно пользователи старых систем могут найти возможность очень большого использования памяти раздражающей. Чтобы предотвратить неприятные неожиданности, xz имеет встроенный лимитер использования памяти, который отключён по умолчанию. Хотя некоторые операционные системы предоставляют способы ограничения использования памяти процессами, полагаться на это не считается достаточно гибким (например, использование ulimit(1) для ограничения виртуальной памяти склонно нарушать mmap(2)). Лимитер использования памяти можно включить с помощью опции командной строки --memlimit=limit. Часто удобнее включить лимитер по умолчанию, установив переменную окружения XZ_DEFAULTS, например, XZ_DEFAULTS=--memlimit=150MiB. Возможна установка лимитов отдельно для сжатия и распаковки с помощью --memlimit-compress=limit и --memlimit-decompress=limit. Использование этих двух опций вне XZ_DEFAULTS редко полезно, поскольку один запуск xz не может выполнять и сжатие, и распаковку, и --memlimit=limit (или -M limit) короче для ввода в командной строке. Если указанный лимит использования памяти превышен при распаковке, xz выведет ошибку и распаковка файла не удастся. Если лимит превышен при сжатии, xz попытается уменьшить настройки так, чтобы лимит больше не превышался (кроме случаев использования --format=raw или --no-adjust). Таким образом, операция не завершится неудачей, если лимит не очень мал. Масштабирование настроек выполняется в шагах, которые не соответствуют пресетам уровня сжатия, например, если лимит немного меньше количества, необходимого для xz -9, настройки будут уменьшены только немного, а не до xz -8. Конкатенация и заполнение для файлов .xz Возможна конкатенация файлов .xz как есть. xz будет распаковывать такие файлы, как будто они являются одним файлом .xz. Возможна вставка заполнения между конкатенированными частями или после последней части. Заполнение должно состоять из нулевых байтов, и размер заполнения должен быть кратным четырём байтам. Это может быть полезно, например, если файл .xz хранится на носителе, который измеряет размеры файлов в блоках по 512 байт. Конкатенация и заполнение не разрешены для файлов .lzma или необработанных потоков. OPTIONS Суффиксы целых чисел и специальные значения В большинстве мест, где ожидается аргумент целого числа, поддерживается необязательный суффикс для лёгкого указания больших целых чисел. Между целым числом и суффиксом не должно быть пробелов. KiB Умножить целое число на 1 024 (2^10). Ki, k, kB, K и KB принимаются как синонимы для KiB. MiB Умножить целое число на 1 048 576 (2^20). Mi, m, M и MB принимаются как синонимы для MiB. GiB Умножить целое число на 1 073 741 824 (2^30). Gi, g, G и GB принимаются как синонимы для GiB. Специальное значение max может использоваться для указания максимального целочисленного значения, поддерживаемого опцией. Режим операции Если несколько опций режима операции указаны, последняя вступает в силу. -z, --compress Сжатие. Это режим операции по умолчанию, когда ни одна опция режима операции не указана и другой режим операции не подразумевается из имени команды (например, unxz подразумевает --decompress). После успешного сжатия исходный файл удаляется, если не запись в стандартный вывод или не указан --keep. -d, --decompress, --uncompress Распаковка. После успешной распаковки исходный файл удаляется, если не запись в стандартный вывод или не указан --keep. -t, --test Проверить целостность сжатых файлов. Эта опция эквивалентна --decompress --stdout, за исключением того, что распакованные данные отбрасываются вместо записи в стандартный вывод. Файлы не создаются и не удаляются. -l, --list Вывести информацию о сжатых файлах. Несжатый вывод не производится, и файлы не создаются или не удаляются. В режиме списка программа не может читать сжатые данные из стандартного ввода или из других неподвижных источников. По умолчанию список показывает базовую информацию о файлах, один файл на строку. Для получения более подробной информации используйте также опцию --verbose. Для ещё большего количества информации используйте --verbose дважды, но учтите, что это может быть медленно, поскольку получение всей дополнительной информации требует многих поисков. Ширина подробного вывода превышает 80 символов, поэтому перенаправление вывода, например, в less -S, может быть удобным, если терминал недостаточно широкий. Точный вывод может варьироваться между версиями xz и разными локалями. Для машинно-читаемого вывода используйте --robot --list. Модификаторы операции -k, --keep Не удалять входные файлы. С версии xz 5.2.6 эта опция также заставляет xz сжимать или распаковывать, даже если вход - это символическая ссылка на обычный файл, имеет более одной жёсткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. В более ранних версиях это делалось только с --force. -f, --force Эта опция имеет несколько эффектов: • Если целевой файл уже существует, удалить его перед сжатием или распаковкой. • Сжимать или распаковывать, даже если вход - это символическая ссылка на обычный файл, имеет более одной жёсткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. • При использовании с --decompress --stdout и xz не может распознать тип исходного файла, скопировать исходный файл как есть в стандартный вывод. Это позволяет использовать xzcat --force как cat(1) для файлов, которые не были сжаты с xz. Обратите внимание, что в будущем xz может поддерживать новые сжатые форматы файлов, что может заставить xz распаковывать больше типов файлов вместо копирования их как есть в стандартный вывод. --format=format можно использовать для ограничения xz распаковкой только одного формата файла. -c, --stdout, --to-stdout Записывать сжатые или распакованные данные в стандартный вывод вместо файла. Это подразумевает --keep. --single-stream Распаковывать только первый поток .xz и молча игнорировать возможные оставшиеся входные данные после потока. Нормально такие завершающие мусорные данные заставляют xz выводить ошибку. xz никогда не распаковывает более одного потока из файлов .lzma или необработанных потоков, но эта опция всё равно заставляет xz игнорировать возможные завершающие данные после файла .lzma или необработанного потока. Эта опция не имеет эффекта, если режим операции не --decompress или --test. --no-sparse Отключить создание разреженных файлов. По умолчанию, если распаковка в обычный файл, xz попытается сделать файл разреженным, если распакованные данные содержат длинные последовательности двоичных нулей. Это также работает при записи в стандартный вывод, если стандартный вывод подключён к обычному файлу и выполняются определённые дополнительные условия для безопасности. Создание разреженных файлов может сэкономить место на диске и ускорить распаковку, уменьшив объём ввода-вывода диска. -S .suf, --suffix=.suf При сжатии, использовать .suf как суффикс для целевого файла вместо .xz или .lzma. Если не запись в стандартный вывод и исходный файл уже имеет суффикс .suf, выводится предупреждение и файл пропускается. При распаковке, распознавать файлы с суффиксом .suf в дополнение к файлам с суффиксами .xz, .txz, .lzma, .tlz или .lz. Если исходный файл имеет суффикс .suf, суффикс удаляется, чтобы получить имя целевого файла. При сжатии или распаковке необработанных потоков (--format=raw) суффикс всегда должен быть указан, если не запись в стандартный вывод, поскольку для необработанных потоков нет суффикса по умолчанию. --files[=file] Читать имена файлов для обработки из file; если file опущен, имена файлов читаются из стандартного ввода. Имена файлов должны завершаться символом новой строки. Точка (-) воспринимается как обычное имя файла; это не означает стандартный ввод. Если имена файлов также указаны в аргументах командной строки, они обрабатываются перед именами файлов, прочитанными из file. --files0[=file] Это идентично --files[=file], за исключением того, что каждое имя файла должно завершаться нулевым символом. Базовые опции формата файла и сжатия -F format, --format=format Указать формат файла для сжатия или распаковки: auto Это значение по умолчанию. При сжатии, auto эквивалентно xz. При распаковке, формат входного файла определяется автоматически. Обратите внимание, что необработанные потоки (созданные с --format=raw) не могут быть автоматически обнаружены. xz Сжимать в формат файла .xz или принимать только файлы .xz при распаковке. lzma, alone Сжимать в устаревший формат файла .lzma или принимать только файлы .lzma при распаковке. Альтернативное имя alone предоставлено для обратной совместимости с LZMA Utils. lzip Принимать только файлы .lz при распаковке. Сжатие не поддерживается. Поддерживаются версия формата 0 и нерасширенная версия 1. Файлы версии 0 создавались lzip 1.3 и старше. Такие файлы не распространены, но могут быть найдены в архивах файлов, поскольку несколько исходных пакетов были выпущены в этом формате. Люди могут иметь старые личные файлы в этом формате. Поддержка распаковки версии формата 0 была удалена в lzip 1.18. lzip 1.4 и новее создают файлы в формате версии 1. Расширение маркера синхронизированного сброса для версии формата 1 было добавлено в lzip 1.6. Это расширение редко используется и не поддерживается xz (диагностируется как повреждённый вход). raw Сжимать или распаковывать необработанный поток (без заголовков). Это предназначено только для продвинутых пользователей. Чтобы декодировать необработанные потоки, вам нужно использовать --format=raw и явно указать цепочку фильтров, которая обычно хранилась бы в заголовках контейнера. -C check, --check=check Указать тип проверки целостности. Проверка вычисляется из несжатых данных и хранится в файле .xz. Эта опция имеет эффект только при сжатии в формат .xz; формат .lzma не поддерживает проверки целостности. Проверка целостности (если есть) проверяется при распаковке файла .xz. Поддерживаемые типы проверок: none Не вычислять проверку целостности вообще. Это обычно плохая идея. Это может быть полезно, когда целостность данных проверяется другими средствами в любом случае. crc32 Вычислить CRC32 с использованием полинома из IEEE-802.3 (Ethernet). crc64 Вычислить CRC64 с использованием полинома из ECMA-182. Это значение по умолчанию, поскольку оно немного лучше, чем CRC32, для обнаружения повреждённых файлов, а разница в скорости незначительна. sha256 Вычислить SHA-256. Это немного медленнее, чем CRC32 и CRC64. Целостность заголовков .xz всегда проверяется с CRC32. Это не возможно изменить или отключить. --ignore-check Не проверять проверку целостности сжатых данных при распаковке. Значения CRC32 в заголовках .xz всё равно будут проверены нормально. Не используйте эту опцию, если вы не знаете, что делаете. Возможные причины использования этой опции: • Попытка восстановить данные из повреждённого файла .xz. • Увеличение скорости распаковки. Это имеет значение в основном с SHA-256 или с файлами, которые сжаты очень хорошо. Рекомендуется не использовать эту опцию для этой цели, если целостность файла не проверяется внешне другим способом. -0 ... -9 Выбрать пресет уровня сжатия. По умолчанию -6. Если указано несколько пресетов уровней, последний вступает в силу. Если уже указана пользовательская цепочка фильтров, установка пресета уровня сжатия очищает пользовательскую цепочку фильтров. Различия между пресетами более значительны, чем с gzip(1) и bzip2(1). Выбранные настройки сжатия определяют требования к памяти декомпрессора, таким образом, использование слишком высокого пресета уровня может сделать болезненным распаковку файла на старой системе с малым количеством RAM. В частности, не стоит слепо использовать -9 для всего, как это часто бывает с gzip(1) и bzip2(1). -0 ... -3 Это относительно быстрые пресеты. -0 иногда быстрее, чем gzip -9, при гораздо лучшем сжатии. Более высокие значения часто имеют скорость, сравнимую с bzip2(1) с соотношением сжатия, сравнимым или лучше, хотя результаты сильно зависят от типа сжимаемых данных. -4 ... -6 Хорошее до очень хорошего сжатия при разумном использовании памяти декомпрессора, даже для старых систем. -6 - это значение по умолчанию, которое обычно является хорошим выбором для распространения файлов, которые должны быть распакованы даже на системах с всего 16 MiB RAM. (-5e или -6e также стоит рассмотреть. Смотрите --extreme.) -7 ... -9 Это как -6, но с более высокими требованиями к памяти компрессора и декомпрессора. Это полезно только при сжатии файлов больше 8 MiB, 16 MiB и 32 MiB соответственно. На том же оборудовании скорость распаковки примерно постоянна в количестве байт сжатых данных в секунду. Другими словами, чем лучше сжатие, тем быстрее обычно будет распаковка. Это также означает, что количество несжатого вывода, произведённого в секунду, может сильно варьироваться. В следующей таблице суммируются особенности пресетов: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Описания столбцов: • DictSize - это размер словаря LZMA2. Это трата памяти использовать словарь больше, чем размер несжатого файла. Именно поэтому хорошо избегать использования пресетов -7 ... -9, когда в них нет реальной необходимости. При -6 и ниже, количество потраченной памяти обычно достаточно мало, чтобы не иметь значения. • CompCPU - это упрощённое представление настроек LZMA2, которые влияют на скорость сжатия. Размер словаря также влияет на скорость, так что, несмотря на то, что CompCPU одинаков для уровней -6 ... -9, более высокие уровни всё равно склонны быть немного медленнее. Чтобы получить ещё более медленное и, возможно, лучшее сжатие, смотрите --extreme. • CompMem содержит требования к памяти компрессора в однопоточном режиме. Это может немного варьироваться между версиями xz. • DecMem содержит требования к памяти декомпрессора. То есть, настройки сжатия определяют требования к памяти декомпрессора. Точное использование памяти декомпрессором немного больше, чем размер словаря LZMA2, но значения в таблице округлены вверх до следующего полного MiB. Требования к памяти в многопоточном режиме значительно выше, чем в однопоточном. С значением --block-size по умолчанию, каждый поток требует 3*3*DictSize плюс CompMem или DecMem. Например, четыре потока с пресетом -6 требуют 660–670 MiB памяти. -e, --extreme Использовать более медленный вариант выбранного пресета уровня сжатия (-0 ... -9), чтобы, hopefully, получить немного лучшее соотношение сжатия, но с неудачей это может сделать его хуже. Использование памяти декомпрессором не затрагивается, но использование памяти компрессором немного увеличивается при пресетах -0 ... -3. Поскольку есть два пресета с размерами словарей 4 MiB и 8 MiB, пресеты -3e и -5e используют немного более быстрые настройки (меньший CompCPU), чем -4e и -6e, соответственно. Таким образом, ни два пресета не идентичны. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB Например, всего четыре пресета используют словарь 8 MiB, порядок от самого быстрого до самого медленного - -5, -6, -5e и -6e. --fast --best Эти являются несколько вводящими в заблуждение псевдонимами для -0 и -9 соответственно. Эти предоставлены только для обратной совместимости с LZMA Utils. Избегайте использования этих опций. --block-size=size При сжатии в формат .xz, разделить входные данные на блоки по size байт. Блоки сжимаются независимо друг от друга, что помогает с многопоточностью и делает возможной ограниченную произвольную доступную распаковку. Эта опция обычно используется для переопределения размера блока по умолчанию в многопоточном режиме, но эту опцию можно использовать и в однопоточном режиме. В многопоточном режиме примерно трижды size байт будут выделены в каждом потоке для буферизации ввода и вывода. Значение по умолчанию - три размера словаря LZMA2 или 1 MiB, в зависимости от того, что больше. Обычно хорошее значение - 2–4 раза размер словаря LZMA2 или как минимум 1 MiB. Использование size меньше размера словаря LZMA2 - трата RAM, поскольку тогда буфер словаря LZMA2 никогда не будет полностью использован. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Эта информация о размере необходима для многопоточной распаковки. В однопоточном режиме разделение блоков по умолчанию не выполняется. Установка этой опции не влияет на использование памяти. Информация о размере не хранится в заголовках блоков, так что файлы, созданные в однопоточном режиме, не будут идентичны файлам, созданным в многопоточном режиме. Отсутствие информации о размере также означает, что xz не сможет распаковывать файлы в многопоточном режиме. --block-list=items При сжатии в формат .xz, начать новый блок с необязательной пользовательской цепочкой фильтров после указанных интервалов несжатых данных. items - это список, разделённый запятыми. Каждый элемент состоит из необязательного номера цепочки фильтров от 0 до 9, за которым следует двоеточие (:) и требуемый размер несжатых данных. Опущение элемента (две или более последовательных запятых) - сокращение для использования размера и фильтров предыдущего элемента. Если входной файл больше суммы размеров в items, последний элемент повторяется до конца файла. Специальное значение 0 может использоваться как последний размер, чтобы указать, что остаток файла должен быть закодирован как один блок. Альтернативную цепочку фильтров для каждого блока можно указать в сочетании с опциями --filters1=filters ... --filters9=filters. Эти опции определяют цепочки фильтров с идентификатором от 1 до 9. Цепочка фильтров 0 можно использовать для ссылки на цепочку фильтров по умолчанию, которая является той же, что и без указания цепочки фильтров. Идентификатор цепочки фильтров можно использовать перед несжатым размером, за которым следует двоеточие (:). Например, если указать --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB, то блоки будут созданы с использованием: • Цепочки фильтров, указанной в --filters1 и 2 MiB ввода. • Цепочки фильтров, указанной в --filters3 и 2 MiB ввода. • Цепочки фильтров, указанной в --filters2 и 4 MiB ввода. • Цепочки фильтров, указанной в --filters2 и 4 MiB ввода. • Цепочки фильтров по умолчанию и 2 MiB ввода. • Цепочки фильтров по умолчанию и 4 MiB ввода для каждого блока до конца ввода. Если указать размер, превышающий размер блока энкодера (либо значение по умолчанию в многопоточном режиме, либо значение, указанное с --block-size=size), энкодер создаст дополнительные блоки, сохраняя границы, указанные в items. Например, если указать --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB и входной файл - 80 MiB, получите 11 блоков: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10 и 1 MiB. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Это не делается в однопоточном режиме, так что закодированный вывод не будет идентичен тому, что в многопоточном режиме. --flush-timeout=timeout При сжатии, если прошло более timeout миллисекунд (положительное целое число) с предыдущего сброса и чтение большего количества ввода заблокировано, все ожидающие входные данные сбрасываются из энкодера и становятся доступными в выходном потоке. Это может быть полезно, если xz используется для сжатия данных, которые передаются по сети. Малые значения timeout делают данные доступными на приёмной стороне с малой задержкой, но большие значения дают лучшее соотношение сжатия. Эта функция отключена по умолчанию. Если эта опция указана более одного раза, последняя вступает в силу. Специальное значение timeout 0 можно использовать для явного отключения этой функции. Эта функция недоступна в не-POSIX системах. Эта функция всё ещё экспериментальна. В настоящее время xz непригодно для распаковки потока в реальном времени из-за того, как xz выполняет буферизацию. --memlimit-compress=limit Установить лимит использования памяти для сжатия. Если эта опция указана несколько раз, последняя вступает в силу. Если настройки сжатия превышают лимит, xz попытается скорректировать настройки вниз, чтобы лимит больше не превышался, и выведет уведомление о том, что автоматическая корректировка была произведена. Корректировки производятся в следующем порядке: уменьшение количества потоков, переключение в однопоточный режим, если даже один поток в многопоточном режиме превышает лимит, и, наконец, уменьшение размера словаря LZMA2. При сжатии с --format=raw или если указан --no-adjust, может быть уменьшено только количество потоков, поскольку это можно сделать без влияния на сжатый вывод. Если лимит не может быть достигнут даже с корректировками, описанными выше, выводится ошибка и xz завершится с кодом выхода 1. Лимит можно указать несколькими способами: • Лимит может быть абсолютным значением в байтах. Использование суффикса целого числа, такого как MiB, может быть полезным. Пример: --memlimit-compress=80MiB • Лимит может быть указан как процент от общего физического объёма памяти (RAM). Это может быть полезно, особенно при установке переменной окружения XZ_DEFAULTS в скрипте инициализации оболочки, который делится между разными компьютерами. Таким образом лимит автоматически больше на системах с большим количеством памяти. Пример: --memlimit-compress=70% • Лимит можно сбросить обратно к значению по умолчанию, установив его на 0. В настоящее время это эквивалентно установке лимита на max (нет лимита использования памяти). Для 32-разрядного xz есть специальный случай: если лимит будет больше 4020 MiB, лимит устанавливается на 4020 MiB. На MIPS32 используется 2000 MiB вместо этого. (Значения 0 и max не затрагиваются этим. Аналогичная функция не существует для распаковки.) Это может быть полезно, когда 32-разрядный исполняемый файл имеет доступ к адресу 4 GiB пространства (2 GiB на MIPS32), в то время как, hopefully, не нанося вреда в других ситуациях. Смотрите также раздел Использование памяти. --memlimit-decompress=limit Установить лимит использования памяти для распаковки. Это также влияет на режим --list. Если операция невозможна без превышения лимита, xz выведет ошибку и распаковка файла не удастся. Смотрите --memlimit-compress=limit для возможных способов указания лимита. --memlimit-mt-decompress=limit Установить лимит использования памяти для многопоточной распаковки. Это может повлиять только на количество потоков; это никогда не заставит xz отказаться от распаковки файла. Если limit слишком низкий, чтобы позволить какое-либо многопоточность, лимит игнорируется и xz продолжит в однопоточном режиме. Обратите внимание, что если также используется --memlimit-decompress, он всегда применяется к обоим однопоточному и многопоточному режимам, так что эффективный лимит для многопоточности никогда не будет выше, чем лимит, установленный с --memlimit-decompress. В отличие от других опций лимита использования памяти, --memlimit-mt-decompress=limit имеет системно-специфичное значение по умолчанию. xz --info-memory можно использовать, чтобы увидеть текущее значение. Эта опция и её значение по умолчанию существуют, потому что без любого лимита многопоточный декомпрессор может в конечном итоге выделить безумное количество памяти с некоторыми входными файлами. Если значение лимита по умолчанию слишком низкое на вашей системе, не стесняйтесь увеличить лимит, но никогда не устанавливайте его на значение больше, чем объём используемой RAM, поскольку с подходящими входными файлами xz попытается использовать это количество памяти даже с небольшим количеством потоков. Выход за пределы памяти или свапинг не улучшит производительность распаковки. Смотрите --memlimit-compress=limit для возможных способов указания лимита. Установка limit на 0 сбрасывает лимит на системно-специфичное значение по умолчанию. -M limit, --memlimit=limit, --memory=limit Это эквивалентно указанию --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Вывести ошибку и выйти, если лимит использования памяти не может быть достигнут без корректировки настроек, которые влияют на сжатый вывод. То есть, это предотвращает xz от переключения энкодера из многопоточного режима в однопоточный режим и от уменьшения размера словаря LZMA2. Даже при использовании этой опции количество потоков может быть уменьшено, чтобы соответствовать лимиту использования памяти, поскольку это не повлияет на сжатый вывод. Автоматическая корректировка всегда отключена при создании необработанных потоков (--format=raw). -T threads, --threads=threads Указать количество рабочих потоков. Установка threads на специальное значение 0 заставляет xz использовать до такого количества потоков, сколько процессор(ы) системы поддерживают. Фактическое количество потоков может быть меньше, чем threads, если входной файл недостаточно большой для потоков с заданными настройками или если использование большего количества потоков превысит лимит использования памяти. Однопоточный и многопоточный компрессоры производят разный вывод. Однопоточный компрессор даст самый маленький размер файла, но только вывод из многопоточного компрессора можно распаковывать с использованием нескольких потоков. Установка threads на 1 использует однопоточный режим. Установка threads на любое другое значение, включая 0, использует многопоточный компрессор, даже если система поддерживает только один аппаратный поток. (xz 5.2.x использовал однопоточный режим в этой ситуации.) Чтобы использовать многопоточный режим с одним потоком, установите threads на +1. Префикс + не имеет эффекта с значениями, отличными от 1. Лимит использования памяти всё равно может заставить xz переключиться в однопоточный режим, если не используется --no-adjust. Поддержка префикса + была добавлена в xz 5.4.0. Если запрошено автоматическое количество потоков и лимит использования памяти не указан, будет использован системно-специфичный лимит по умолчанию, чтобы, возможно, ограничить количество потоков. Это мягкий лимит в том смысле, что он игнорируется, если количество потоков становится одним, так что мягкий лимит никогда не остановит xz от сжатия или распаковки. Этот лимит по умолчанию не заставит xz переключиться из многопоточного режима в однопоточный режим. Активные лимиты можно увидеть с xz --info-memory. В настоящее время единственный метод потоков - разделить вход на блоки и сжать их независимо друг от друга. Размер блока по умолчанию зависит от уровня сжатия и может быть переопределён с помощью опции --block-size=size. Многопоточная распаковка работает только с файлами, которые содержат несколько блоков с информацией о размере в заголовках блоков. Все достаточно большие файлы, сжатые в многопоточном режиме, соответствуют этому условию, но файлы, сжатые в однопоточном режиме, нет, даже если использовался --block-size=size. Значение threads по умолчанию - 0. В xz 5.4.x и старше значение по умолчанию - 1. Пользовательские цепочки фильтров компрессора Пользовательская цепочка фильтров позволяет указывать настройки сжатия в деталях вместо использования настроек, связанных с пресетами. Когда указана пользовательская цепочка фильтров, опции пресетов (-0 ... -9 и --extreme), указанные ранее в командной строке, забываются. Если опция пресета указана после одной или более опций пользовательской цепочки фильтров, новый пресет вступает в силу, и пользовательские опции цепочки фильтров, указанные ранее, забываются. Цепочка фильтров сравнима с конвейером в командной строке. При сжатии, несжатый вход идёт в первый фильтр, чей вывод идёт в следующий фильтр (если есть). Вывод последнего фильтра записывается в сжатый файл. Максимальное количество фильтров в цепочке - четыре, но обычно цепочка фильтров имеет только один или два фильтра. Многие фильтры имеют ограничения на то, где они могут быть в цепочке фильтров: некоторые фильтры могут работать только как последний фильтр в цепочке, некоторые только как нефинальный фильтр, и некоторые работают в любом положении в цепочке. В зависимости от фильтра, это ограничение либо inherent к дизайну фильтра, либо существует для предотвращения проблем безопасности. Пользовательскую цепочку фильтров можно указать двумя разными способами. Опции --filters=filters и --filters1=filters ... --filters9=filters позволяют указывать всю цепочку фильтров в одной опции с использованием синтаксиса строки фильтров liblzma. В качестве альтернативы, цепочку фильтров можно указать, используя одну или более индивидуальных опций фильтров в порядке, в котором они желаемы. То есть, порядок индивидуальных опций фильтров значим! При декодировании необработанных потоков (--format=raw), цепочка фильтров должна быть указана в том же порядке, в котором она была указана при сжатии. Любые индивидуальные опции фильтров или пресеты, указанные до полной опции цепочки (--filters=filters), будут забыты. Индивидуальные фильтры, указанные после полной опции цепочки, сбросят цепочку фильтров. Как полные, так и индивидуальные опции фильтров принимают опции, специфичные для фильтра, в виде списка, разделённого запятыми. Дополнительные запятые в опциях игнорируются. Каждая опция имеет значение по умолчанию, так что укажите те, которые вы хотите изменить. Чтобы увидеть всю цепочку фильтров и опции, используйте xz -vv (то есть, используйте --verbose дважды). Это работает также для просмотра опций цепочки фильтров, используемых пресетами. --filters=filters Указать полную цепочку фильтров или пресет в одной опции. Каждый фильтр может быть разделён пробелами или двумя тире (--). filters может потребоваться заключить в кавычки в командной строке оболочки, чтобы оно анализировалось как одна опция. Чтобы обозначить опции, используйте : или =. Пресет можно предварить с -, а затем следовать нулю или более флагам. Единственный поддерживаемый флаг - e для применения тех же опций, что и --extreme. --filters1=filters ... --filters9=filters Указать до девяти дополнительных цепочек фильтров, которые можно использовать с --block-list. Например, при сжатии архива с исполняемыми файлами, за которыми следуют текстовые файлы, исполняемая часть может использовать цепочку фильтров с фильтром BCJ, а текстовая часть - только фильтр LZMA2. --filters-help Вывести сообщение помощи, описывающее, как указывать пресеты и пользовательские цепочки фильтров в опциях --filters и --filters1=filters ... --filters9=filters, и успешно выйти. --lzma1[=options] --lzma2[=options] Добавить фильтр LZMA1 или LZMA2 в цепочку фильтров. Эти фильтры могут использоваться только как последний фильтр в цепочке. LZMA1 - это устаревший фильтр, который поддерживается почти исключительно из-за устаревшего формата файла .lzma, который поддерживает только LZMA1. LZMA2 - это обновлённая версия LZMA1 для исправления некоторых практических проблем LZMA1. Формат .xz использует LZMA2 и не поддерживает LZMA1 вообще. Скорость и соотношение сжатия LZMA1 и LZMA2 практически одинаковы. LZMA1 и LZMA2 делят один и тот же набор опций: preset=preset Сбросить все опции LZMA1 или LZMA2 на preset. Preset состоит из целого числа, за которым может следовать модификаторы пресета в виде одиночной буквы. Целое число может быть от 0 до 9, соответствующее опциям командной строки -0 ... -9. Единственный поддерживаемый модификатор в настоящее время - e, который соответствует --extreme. Если пресет не указан, значения опций LZMA1 или LZMA2 по умолчанию берутся из пресета 6. dict=size Размер словаря (буфера истории) указывает, сколько байт недавно обработанных несжатых данных хранится в памяти. Алгоритм пытается найти повторяющиеся последовательности байт (совпадения) в несжатых данных и заменить их ссылками на данные, в настоящее время в словаре. Чем больше словарь, тем выше шанс найти совпадение. Таким образом, увеличение размера словаря обычно улучшает соотношение сжатия, но словарь больше, чем несжатый файл, - трата памяти. Типичный размер словаря - от 64 KiB до 64 MiB. Минимум - 4 KiB. Максимум для сжатия в настоящее время 1.5 GiB (1536 MiB). Декомпрессор уже поддерживает словари до одного байта меньше 4 GiB, что является максимумом для форматов потоков LZMA1 и LZMA2. Размер словаря и поисковик совпадений (mf) вместе определяют использование памяти энкодером LZMA1 или LZMA2. Тот же (или больший) размер словаря требуется для распаковки, который использовался при сжатии, таким образом, использование памяти декомпрессором определяется размером словаря, использованным при сжатии. Заголовки .xz хранят размер словаря либо как 2^n, либо как 2^n + 2^(n-1), так что эти размеры немного предпочтительны для сжатия. Другие размеры будут округлены вверх при хранении в заголовках .xz. lc=lc Указать количество бит контекста литералов. Минимум - 0, а максимум - 4; значение по умолчанию - 3. Кроме того, сумма lc и lp не должна превышать 4. Все байты, которые не могут быть закодированы как совпадения, кодируются как литералы. То есть, литералы - просто 8-битные байты, которые кодируются по одному. Литеральное кодирование предполагает, что самые высокие lc биты предыдущего несжатого байта коррелируют со следующим байтом. Например, в типичном английском тексте заглавная буква часто followed нижней буквой, а нижняя буква обычно followed другой нижней буквой. В наборе символов US-ASCII самые высокие три бита - 010 для заглавных букв и 011 для строчных букв. Когда lc как минимум 3, литерное кодирование может использовать это свойство в несжатых данных. Значение по умолчанию (3) обычно хорошее. Если вы хотите максимальное сжатие, протестируйте lc=4. Иногда это помогает немного, а иногда делает сжатие хуже. Если это делает хуже, протестируйте lc=2 тоже. lp=lp Указать количество бит позиции литералов. Минимум - 0, а максимум - 4; значение по умолчанию - 0. lp влияет на то, какой выравнивание в несжатых данных предполагается при кодировании литералов. Смотрите pb ниже для дополнительной информации о выравнивании. pb=pb Указать количество бит позиции. Минимум - 0, а максимум - 4; значение по умолчанию - 2. pb влияет на то, какой выравнивание в несжатых данных предполагается в общем. Значение по умолчанию означает четырёхбайтное выравнивание (2^pb=2^2=4), что часто является хорошим выбором, когда нет лучшей догадки. Когда выравнивание известно, установка pb соответственно может немного уменьшить размер файла. Например, с текстовыми файлами, имеющими однобайтовое выравнивание (US-ASCII, ISO-8859-*, UTF-8), установка pb=0 может немного улучшить сжатие. Для текста UTF-16 pb=1 - хороший выбор. Если выравнивание - нечётное число, как 3 байта, pb=0 может быть лучшим выбором. Даже если предполагаемое выравнивание можно скорректировать с помощью pb и lp, LZMA1 и LZMA2 всё равно немного предпочитают 16-байтовое выравнивание. Стоит учитывать это при проектировании форматов файлов, которые, вероятно, часто будут сжиматься с LZMA1 или LZMA2. mf=mf Поисковик совпадений сильно влияет на скорость энкодера, использование памяти и соотношение сжатия. Обычно поисковики совпадений Hash Chain быстрее, чем Binary Tree поисковики совпадений. Значение по умолчанию зависит от пресета: 0 использует hc3, 1–3 используют hc4, а остальные - bt4. Поддерживаются следующие поисковики совпадений. Формулы использования памяти ниже - грубые приближения, которые ближе к реальности, когда dict - степень двойки. hc3 Hash Chain с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 7.5 (если dict <= 16 MiB); dict * 5.5 + 64 MiB (если dict > 16 MiB) hc4 Hash Chain с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 7.5 (если dict <= 32 MiB); dict * 6.5 (если dict > 32 MiB) bt2 Binary Tree с хэшированием 2-байтовым Минимальное значение для nice: 2 Использование памяти: dict * 9.5 bt3 Binary Tree с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 11.5 (если dict <= 16 MiB); dict * 9.5 + 64 MiB (если dict > 16 MiB) bt4 Binary Tree с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 11.5 (если dict <= 32 MiB); dict * 10.5 (если dict > 32 MiB) mode=mode Режим сжатия указывает метод анализа данных, произведённых поисковиком совпадений. Поддерживаемые режимы - fast и normal. Значение по умолчанию - fast для пресетов 0–3 и normal для пресетов 4–9. Обычно fast используется с поисковиками совпадений Hash Chain и normal с поисковиками совпадений Binary Tree. Это также то, что делают пресеты. nice=nice Указать, что считается хорошей длиной для совпадения. Как только найдено совпадение как минимум nice байт, алгоритм перестаёт искать, возможно, лучшие совпадения. nice может быть 2–273 байта. Более высокие значения склонны давать лучшее соотношение сжатия за счёт скорости. Значение по умолчанию зависит от пресета. depth=depth Указать максимальную глубину поиска в поисковике совпадений. Значение по умолчанию - специальное значение 0, которое заставляет компрессор определить разумную глубину из mf и nice. Разумная глубина для Hash Chains - 4–100, а для Binary Trees - 16–1000. Использование очень высоких значений для depth может сделать энкодер крайне медленным с некоторыми файлами. Избегайте установки depth больше 1000, если вы готовы прервать сжатие в случае, если оно занимает слишком много времени. При декодировании необработанных потоков (--format=raw), LZMA2 нуждается только в размере словаря. LZMA1 нуждается также в lc, lp и pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Добавить фильтр ветвления/вызова/прыжка (BCJ) в цепочку фильтров. Эти фильтры могут использоваться только как нефинальный фильтр в цепочке. Фильтр BCJ преобразует относительные адреса в машинном коде в их абсолютные аналоги. Это не изменяет размер данных, но увеличивает избыточность, что может помочь LZMA2 произвести 0–15 % меньший файл .xz. Фильтры BCJ всегда обратимы, так что использование фильтра BCJ для неправильного типа данных не приведёт к потере данных, хотя это может сделать соотношение сжатия немного хуже. Фильтры BCJ очень быстрые и используют незначительное количество памяти. Эти фильтры BCJ имеют известные проблемы, связанные со соотношением сжатия: • Некоторые типы файлов, содержащие исполняемый код (например, объектные файлы, статические библиотеки и модули ядра Linux) имеют адреса в инструкциях, заполненные значениями-заполнителями. Эти фильтры BCJ всё равно будут выполнять преобразование адреса, что сделает сжатие хуже для этих файлов. • Если фильтр BCJ применяется к архиву, возможно, что это сделает соотношение сжатия хуже, чем без использования фильтра BCJ. Например, если в архиве есть похожие или даже идентичные исполняемые файлы, то фильтрация, вероятно, сделает файлы менее похожими, и, следовательно, сжатие хуже. Содержимое нефайловых файлов в том же архиве тоже может иметь значение. На практике нужно попробовать с и без фильтра BCJ, чтобы увидеть, что лучше в каждой ситуации. Разные наборы инструкций имеют разное выравнивание: исполняемый файл должен быть выровнен по кратному этого значения во входных данных, чтобы фильтр работал. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit или 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte выравнивание лучше PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Поскольку отфильтрованные фильтром BCJ данные обычно сжимаются с LZMA2, соотношение сжатия может быть немного улучшено, если опции LZMA2 установлены так, чтобы соответствовать выравниванию выбранного фильтра BCJ. Примеры: • Фильтр IA-64 имеет выравнивание 16 байт, так что pb=4,lp=4,lc=0 хороши с LZMA2 (2^4=16). • Код RISC-V имеет выравнивание 2 байта или 4 байта в зависимости от того, содержит ли файл 16-битные сжатые инструкции (расширение C). При использовании 16-битных инструкций pb=2,lp=1,lc=3 или pb=1,lp=1,lc=3 хороши. При отсутствии 16-битных инструкций pb=2,lp=2,lc=2 - лучшее. readelf -h можно использовать, чтобы проверить, появляется ли "RVC" на строке "Flags". • ARM64 всегда имеет выравнивание 4 байта, так что pb=2,lp=2,lc=2 - лучшее. • Фильтр x86 - исключение. Обычно хорошо придерживаться значений по умолчанию LZMA2 (pb=2,lp=0,lc=3) при сжатии исполняемых файлов x86. Все фильтры BCJ поддерживают одни и те же опции: start=offset Указать начальный смещение, которое используется при преобразовании между относительными и абсолютными адресами. Смещение должно быть кратным выравниванию фильтра (см. таблицу выше). Значение по умолчанию - ноль. На практике, значение по умолчанию хорошее; указание пользовательского смещения почти никогда не полезно. --delta[=options] Добавить фильтр Delta в цепочку фильтров. Фильтр Delta может использоваться только как нефинальный фильтр в цепочке. В настоящее время поддерживается только простое байтовое вычисление дельты. Это может быть полезно при сжатии, например, несжатых растровых изображений или несжатого PCM-аудио. Однако, специальные алгоритмы могут дать значительно лучшие результаты, чем Delta + LZMA2. Это верно, особенно для аудио, которое сжимается быстрее и лучше, например, с flac(1). Поддерживаемые опции: dist=distance Указать расстояние вычисления дельты в байтах. distance должно быть 1–256. Значение по умолчанию - 1. Например, с dist=2 и входом из восьми байт A1 B1 A2 B3 A3 B5 A4 B7 вывод будет A1 B1 01 02 01 02 01 02. Другие опции -q, --quiet Подавить предупреждения и уведомления. Укажите это дважды, чтобы подавить ошибки тоже. Эта опция не влияет на код выхода. То есть, даже если предупреждение было подавлено, код выхода для указания предупреждения всё равно используется. -v, --verbose Быть многословным. Если стандартный вывод ошибок подключён к терминалу, xz отобразит индикатор прогресса. Указание --verbose дважды даст ещё более многословный вывод. Индикатор прогресса показывает следующую информацию: • Процент завершения показывается, если размер входного файла известен. То есть, процент не может быть показан в трубах. • Количество сжатых данных, произведённых (сжатие) или потреблённых (распаковка). • Количество несжатых данных, потреблённых (сжатие) или произведённых (распаковка). • Соотношение сжатия, которое вычисляется путём деления количества обработанных сжатых данных на количество обработанных несжатых данных. • Скорость сжатия или распаковки. Это измеряется как количество несжатых данных, потреблённых (сжатие) или произведённых (распаковка) в секунду. Это показывается после того, как прошло несколько секунд с момента запуска xz обработки файла. • Прошедшее время в формате M:SS или H:MM:SS. • Оставшееся оценочное время показывается только тогда, когда размер входного файла известен и прошло несколько секунд с момента запуска xz обработки файла. Время показано в менее точном формате, который никогда не имеет двоеточий, например, 2 min 30 s. Когда стандартный вывод ошибок не является терминалом, --verbose заставит xz выводить имя файла, сжатый размер, несжатый размер, соотношение сжатия и, возможно, скорость и прошедшее время в одну строку в стандартный вывод ошибок после сжатия или распаковки файла. Скорость и прошедшее время включаются только когда операция заняла как минимум несколько секунд. Если операция не завершилась, например, из-за прерывания пользователем, также выводится процент завершения, если размер входного файла известен. -Q, --no-warn Не устанавливать код выхода на 2, даже если обнаружено состояние, заслуживающее предупреждения. Эта опция не влияет на уровень многословности, так что и --quiet, и --no-warn должны быть использованы, чтобы не выводить предупреждения и не изменять код выхода. --robot Выводить сообщения в формате, удобном для разбора машинами. Это предназначено для облегчения написания фронтендов, которые хотят использовать xz вместо liblzma, что может быть в случае с различными скриптами. Вывод с этой опцией включён предназначен для стабильности между выпусками xz. Смотрите раздел Режим робота для деталей. --info-memory Вывести, в человеко-читаемом формате, сколько физической памяти (RAM) и сколько процессорных потоков, по мнению xz, имеет система, и лимиты использования памяти для сжатия и распаковки, и успешно выйти. -h, --help Вывести сообщение помощи, описывающее наиболее часто используемые опции, и успешно выйти. -H, --long-help Вывести сообщение помощи, описывающее все функции xz, и успешно выйти -V, --version Вывести номер версии xz и liblzma в человеко-читаемом формате. Чтобы получить вывод, удобный для разбора машинами, укажите --robot перед --version. ROBOT MODE Режим робота активируется с опцией --robot. Это делает вывод xz проще для разбора другими программами. В настоящее время --robot поддерживается только вместе с --list, --filters-help, --info-memory и --version. В будущем это будет поддерживаться для сжатия и распаковки. Режим списка xz --robot --list использует вывод, разделённый табуляцией. Первый столбец каждой строки имеет строку, которая указывает тип информации, найденной на этой строке: name Это всегда первая строка при начале списка файла. Второй столбец на строке - имя файла. file Эта строка содержит общую информацию о файле .xz. Эта строка всегда печатается после строки name. stream Это тип строки используется только когда указан --verbose. Там столько строк stream, сколько потоков в файле .xz. block Это тип строки используется только когда указан --verbose. Там столько строк block, сколько блоков в файле .xz. Строки block показываются после всех строк stream; разные типы строк не перемежаются. summary Этот тип строки используется только когда указан --verbose дважды. Эта строка печатается после всех строк block. Как и строка file, строка summary содержит общую информацию о файле .xz. totals Эта строка всегда последняя строка вывода списка. Она показывает общие счётчики и размеры. Столбцы строк file: 2. Количество потоков в файле 3. Общее количество блоков в потоке(ах) 4. Сжатый размер файла 5. Несжатый размер файла 6. Соотношение сжатия, например, 0.123. Если соотношение больше 9.999, отображаются три тире (---) вместо соотношения. 7. Список имён проверок целостности, разделённый запятыми. Следующие строки используются для известных типов проверок: None, CRC32, CRC64 и SHA-256. Для неизвестных типов проверок используется Unknown-N, где N - ID проверки в виде десятичного числа (одна или две цифры). 8. Общий размер заполнения потока в файле Столбцы строк stream: 2. Номер потока (первый поток - 1) 3. Количество блоков в потоке 4. Сжатый начальный смещение 5. Несжатый начальный смещение 6. Сжатый размер (не включает заполнение потока) 7. Несжатый размер 8. Соотношение сжатия 9. Имя проверки целостности 10. Размер заполнения потока Столбцы строк block: 2. Номер потока, содержащего этот блок 3. Номер блока относительно начала потока (первый блок - 1) 4. Номер блока относительно начала файла 5. Сжатый начальный смещение относительно начала файла 6. Несжатый начальный смещение относительно начала файла 7. Общий сжатый размер блока (включает заголовки) 8. Несжатый размер 9. Соотношение сжатия 10. Имя проверки целостности Если указан --verbose дважды, дополнительные столбцы включаются в строки block. Эти не отображаются с одним --verbose, потому что получение этой информации требует многих поисков и, следовательно, может быть медленно: 11. Значение проверки целостности в шестнадцатеричном формате 12. Размер заголовка блока 13. Флаги блока: c указывает, что сжатый размер присутствует, а u указывает, что несжатый размер присутствует. Если флаг не установлен, тире (-) показывается вместо этого, чтобы сохранить длину строки фиксированной. Новые флаги могут быть добавлены в конец строки в будущем. 14. Размер фактических сжатых данных в блоке (это исключает заголовок блока, заполнение блока и поля проверки) 15. Количество памяти (в байтах), необходимое для распаковки этого блока с этой версией xz 16. Цепочка фильтров. Обратите внимание, что большинство опций, использованных во время сжатия, не могут быть известны, потому что только опции, которые необходимы для распаковки, хранятся в заголовках .xz. Столбцы строк summary: 2. Количество памяти (в байтах), необходимое для распаковки этого файла с этой версией xz 3. yes или no, указывающее, имеют ли все заголовки блоков как сжатый размер, так и несжатый размер, сохранённые в них С версии xz 5.1.2alpha: 4. Минимальная версия xz, необходимая для распаковки файла Столбцы строк totals: 2. Количество потоков 3. Количество блоков 4. Сжатый размер 5. Несжатый размер 6. Среднее соотношение сжатия 7. Список имён проверок целостности, которые присутствовали в файлах, разделённый запятыми 8. Размер заполнения потока 9. Количество файлов. Это здесь, чтобы сохранить порядок предыдущих столбцов таким же, как в строках file. Если указан --verbose дважды, дополнительные столбцы включаются в строки totals: 10. Максимальное количество памяти (в байтах), необходимое для распаковки файлов с этой версией xz 11. yes или no, указывающее, имеют ли все заголовки блоков как сжатый размер, так и несжатый размер, сохранённые в них С версии xz 5.1.2alpha: 12. Минимальная версия xz, необходимая для распаковки файла Будущие версии могут добавить новые типы строк, и новые столбцы могут быть добавлены к существующим типам строк, но существующие столбцы не будут изменены. Помощь по фильтрам xz --robot --filters-help печатает поддерживаемые фильтры в следующем формате: filter:option=<value>,option=<value>... filter Имя фильтра option Имя опции, специфичной для фильтра value Диапазоны значений чисел появляются как <min-max>. Выборы значений строк показаны в < > и разделены символом |. Каждый фильтр печатается на своей строке. Информация о лимите памяти xz --robot --info-memory печатает одну строку с несколькими столбцами, разделёнными табуляцией: 1. Общий объём физической памяти (RAM) в байтах. 2. Лимит использования памяти для сжатия в байтах (--memlimit-compress). Специальное значение 0 указывает значение по умолчанию, которое для однопоточного режима то же, что и отсутствие лимита. 3. Лимит использования памяти для распаковки в байтах (--memlimit-decompress). Специальное значение 0 указывает значение по умолчанию, которое для однопоточного режима то же, что и отсутствие лимита. 4. С версии xz 5.3.4alpha: Использование памяти для многопоточной распаковки в байтах (--memlimit-mt-decompress). Это никогда не ноль, потому что системно-специфичное значение по умолчанию, показанное в столбце 5, используется, если лимит не указан явно. Это также никогда не больше, чем значение в столбце 3, даже если указано большее значение с --memlimit-mt-decompress. 5. С версии xz 5.3.4alpha: Системно-специфичное значение лимита использования памяти по умолчанию, которое используется для ограничения количества потоков при сжатии с автоматическим количеством потоков (--threads=0) и лимитом использования памяти не указано (--memlimit-compress). Это также используется как значение по умолчанию для --memlimit-mt-decompress. 6. С версии xz 5.3.4alpha: Количество доступных процессорных потоков. В будущем вывод xz --robot --info-memory может иметь больше столбцов, но никогда не больше одной строки. Версия xz --robot --version печатает номер версии xz и liblzma в следующем формате: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Основная версия. YYY Дополнительная версия. Чётные числа стабильны. Нечётные числа - alpha или beta версии. ZZZ Уровень патча для стабильных выпусков или просто счётчик для версий разработки. S Стабильность. 0 - alpha, 1 - beta и 2 - стабильная. S должно быть всегда 2, когда YYY чётное. XYYYZZZS одинаковы в обеих строках, если xz и liblzma из одного выпуска XZ Utils. Примеры: 4.999.9beta - 49990091 и 5.0.0 - 50000002. EXIT STATUS 0 Всё в порядке. 1 Произошла ошибка. 2 Произошло что-то, заслуживающее предупреждения, но реальных ошибок не произошло. Уведомления (не предупреждения или ошибки), выведенные в стандартный вывод ошибок, не влияют на код выхода. ENVIRONMENT xz анализирует списки опций, разделённые пробелами, из переменных окружения XZ_DEFAULTS и XZ_OPT, в этом порядке, перед анализом опций из командной строки. Обратите внимание, что только опции анализируются из переменных окружения; все нефопции игнорируются молча. Анализ выполняется с помощью getopt_long(3), который используется также для аргументов командной строки. XZ_DEFAULTS Пользовательские или системные опции по умолчанию. Обычно это устанавливается в скрипте инициализации оболочки для включения лимитера использования памяти xz по умолчанию. Исключая скрипты инициализации оболочки и подобные специальные случаи, скрипты никогда не должны устанавливать или сбрасывать XZ_DEFAULTS. XZ_OPT Это для передачи опций xz, когда невозможно установить опции непосредственно в командной строке xz. Это случай, когда xz запускается скриптом или инструментом, например, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Скрипты могут использовать XZ_OPT, например, для установки специфичных для скрипта опций сжатия по умолчанию. Всё равно рекомендуется позволить пользователям переопределять XZ_OPT, если это разумно. Например, в скриптах sh(1) можно использовать что-то вроде этого: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY Синтаксис командной строки xz практически является надмножеством lzma, unlzma и lzcat из LZMA Utils 4.32.x. В большинстве случаев возможно заменить LZMA Utils на XZ Utils без нарушения существующих скриптов. Однако есть некоторые несовместимости, которые иногда могут вызвать проблемы. Уровни пресетов сжатия Нумерация пресетов уровней сжатия не идентична в xz и LZMA Utils. Самое важное различие - как размеры словарей сопоставляются с разными пресетами. Размер словаря примерно равен использованию памяти декомпрессором. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB Различия размеров словарей влияют на использование памяти компрессором тоже, но есть некоторые другие различия между LZMA Utils и XZ Utils, которые делают разницу ещё больше: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB Значение пресета по умолчанию в LZMA Utils - -7, в то время как в XZ Utils оно - -6, так что оба используют словарь 8 MiB по умолчанию. Потоковые против нефпотоковых файлов .lzma Несжатый размер файла может храниться в заголовке .lzma. LZMA Utils делает это при сжатии обычных файлов. Альтернатива - отметить, что несжатый размер неизвестен, и использовать маркер конца полезной нагрузки, чтобы указать, где декомпрессор должен остановиться. LZMA Utils использует этот метод, когда несжатый размер неизвестен, что является случаем, например, в трубах. xz поддерживает распаковку файлов .lzma с или без маркера конца полезной нагрузки, но все файлы .lzma, созданные xz, будут использовать маркер конца полезной нагрузки и иметь несжатый размер, отмеченный как неизвестный в заголовке .lzma. Это может быть проблемой в некоторых необычных ситуациях. Например, декомпрессор .lzma в встроенном устройстве может работать только с файлами, которые имеют известный несжатый размер. Если вы столкнётесь с этой проблемой, вам нужно использовать LZMA Utils или LZMA SDK для создания файлов .lzma с известным несжатым размером. Неподдерживаемые файлы .lzma Формат .lzma позволяет значения lc до 8 и значения lp до 4. LZMA Utils может распаковывать файлы с любым lc и lp, но всегда создаёт файлы с lc=3 и lp=0. Создание файлов с другими lc и lp возможно с xz и с LZMA SDK. Реализация фильтра LZMA1 в liblzma требует, чтобы сумма lc и lp не превышала 4. Таким образом, файлы .lzma, которые превышают это ограничение, не могут быть распакованы с xz. LZMA Utils создаёт только файлы .lzma, которые имеют размер словаря 2^n (степень двойки), но принимает файлы с любым размером словаря. liblzma принимает только файлы .lzma, которые имеют размер словаря 2^n или 2^n + 2^(n-1). Это для уменьшения ложных срабатываний при обнаружении файлов .lzma. Эти ограничения не должны быть проблемой на практике, поскольку практически все файлы .lzma были сжаты с настройками, которые liblzma примет. Завершающий мусор При распаковке LZMA Utils молча игнорируют всё после первого потока .lzma. В большинстве ситуаций это - ошибка. Это также означает, что LZMA Utils не поддерживают распаковку сконкатенированных файлов .lzma. Если после первого потока .lzma есть данные, xz считает файл повреждённым, если не использовался --single-stream. Это может нарушить неясные скрипты, которые предполагали, что завершающий мусор игнорируется. NOTES Сжатый вывод может варьироваться Точный сжатый вывод, произведённый из одного и того же несжатого входного файла, может варьироваться между версиями XZ Utils, даже если опции сжатия идентичны. Это потому, что энкодер может быть улучшен (быстрее или лучше сжатие) без влияния на формат файла. Вывод может варьироваться даже между разными сборками одной и той же версии XZ Utils, если используются разные опции сборки. Вышеуказанное означает, что как только --rsyncable будет реализован, результирующие файлы не обязательно будут rsyncable, если старые и новые файлы были сжаты с одной версией xz. Эта проблема может быть исправлена, если часть реализации энкодера будет заморожена, чтобы сохранить rsyncable вывод стабильным между версиями xz. Встроенные декомпрессоры .xz Встроенные реализации декомпрессоров .xz, такие как XZ Embedded, не обязательно поддерживают файлы, созданные с типами проверок целостности, отличными от none и crc32. Поскольку значение по умолчанию - --check=crc64, вам нужно использовать --check=none или --check=crc32 при создании файлов для встроенных систем. За пределами встроенных систем все декомпрессоры формата .xz поддерживают все типы проверок или, по крайней мере, могут распаковывать файл без верификации проверки целостности, если конкретная проверка не поддерживается. XZ Embedded поддерживает фильтры BCJ, но только с смещением начала по умолчанию. EXAMPLES Основы Сжать файл foo в foo.xz с использованием уровня сжатия по умолчанию (-6) и удалить foo, если сжатие успешно: xz foo Распаковать bar.xz в bar и не удалять bar.xz, даже если распаковка успешна: xz -dk bar.xz Создать baz.tar.xz с пресетом -4e (-4 --extreme), который медленнее, чем значение по умолчанию -6, но требует меньше памяти для сжатия и распаковки (48 MiB и 5 MiB соответственно): tar cf - baz | xz -4e > baz.tar.xz Смесь сжатых и несжатых файлов может быть распакована в стандартный вывод с помощью одной команды: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Параллельное сжатие многих файлов На GNU и *BSD find(1) и xargs(1) можно использовать для параллелизации сжатия многих файлов: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 Опция -P xargs(1) устанавливает количество параллельных процессов xz. Лучшее значение для опции -n зависит от того, сколько файлов нужно сжать. Если файлов всего несколько, значение, вероятно, должно быть 1; с десятками тысяч файлов, 100 или даже больше может быть подходящим, чтобы уменьшить количество процессов xz, которые xargs(1) в конечном итоге создаст. Опция -T1 для xz здесь, чтобы заставить его работать в однопоточном режиме, потому что xargs(1) используется для контроля количества параллелизации. Режим робота Вычислить, сколько байт сэкономлено в общей сложности после сжатия нескольких файлов: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' Скрипт может захотеть знать, что он использует достаточно новую версию xz. Следующий скрипт sh(1) проверяет, что номер версии инструмента xz как минимум 5.0.0. Этот метод совместим со старыми beta-версиями, которые не поддерживали опцию --robot: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Установить лимит использования памяти для распаковки с помощью XZ_OPT, но если лимит уже установлен, не увеличивать его: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Пользовательские цепочки фильтров компрессора Самое простое использование пользовательских цепочек фильтров - кастомизация пресета LZMA2. Это может быть полезно, потому что пресеты охватывают только подмножество потенциально полезных комбинаций настроек сжатия. Столбцы CompCPU таблиц из описаний опций -0 ... -9 и --extreme полезны при кастомизации пресетов LZMA2. Вот соответствующие части, собранные из этих двух таблиц: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 Если вы знаете, что файл требует довольно большого словаря (например, 32 MiB), чтобы сжиматься хорошо, но вы хотите сжимать его быстрее, чем xz -8, пресет с низким значением CompCPU (например, 1) можно изменить, чтобы использовать больший словарь: xz --lzma2=preset=1,dict=32MiB foo.tar С некоторыми файлами вышеуказанная команда может быть быстрее, чем xz -6, в то время как сжимает значительно лучше. Однако, стоит подчеркнуть, что только некоторые файлы受益 от большого словаря, сохраняя значение CompCPU низким. Самая очевидная ситуация, где большой словарь может сильно помочь - архив, содержащий очень похожие файлы по несколько мегабайт каждый. Размер словаря должен быть значительно больше любого индивидуального файла, чтобы позволить LZMA2 полностью использовать сходства между последовательными файлами. Если очень высокое использование памяти компрессором и декомпрессором допустимо, и файл, который сжимается, как минимум несколько сотен мегабайт, может быть полезно использовать даже больший словарь, чем 64 MiB, который использовал бы xz -9: xz -vv --lzma2=dict=192MiB big_foo.tar Использование -vv (--verbose --verbose), как в вышеуказанном примере, может быть полезным, чтобы увидеть требования к памяти компрессора и декомпрессора. Помните, что использование словаря больше, чем размер несжатого файла - трата памяти, так что вышеуказанная команда не полезна для маленьких файлов. Иногда время сжатия не имеет значения, но использование памяти декомпрессором должно быть сохранено низким, например, чтобы сделать возможным распаковку файла на встроенной системе. Следующая команда использует -6e (-6 --extreme) как базу и устанавливает словарь только на 64 KiB. Результирующий файл может быть распакован с XZ Embedded (вот почему там --check=crc32) с использованием около 100 KiB памяти. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo Если вы хотите выжать как можно больше байт, корректировка количества бит контекста литералов (lc) и количества бит позиции (pb) иногда может помочь. Корректировка количества бит позиции литералов (lp) может помочь тоже, но обычно lc и pb важнее. Например, архив исходного кода содержит в основном текст US-ASCII, так что что-то вроде следующего может дать немного (как 0.1 %) меньший файл, чем xz -6e (попробуйте также без lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Использование другого фильтра вместе с LZMA2 может улучшить сжатие с определёнными типами файлов. Например, чтобы сжать x86-32 или x86-64 разделяемую библиотеку с использованием фильтра BCJ x86: xz --x86 --lzma2 libfoo.so Обратите внимание, что порядок опций фильтров значим. Если --x86 указано после --lzma2, xz выдаст ошибку, потому что не может быть никакого фильтра после LZMA2, и также потому, что фильтр BCJ x86 не может использоваться как последний фильтр в цепочке. Фильтр Delta вместе с LZMA2 может дать хорошие результаты с растровыми изображениями. Он обычно должен превзойти PNG, который имеет несколько продвинутых фильтров, чем простой дельта, но использует Deflate для фактического сжатия. Изображение должно быть сохранено в несжатом формате, например, как несжатый TIFF. Параметр расстояния фильтра Delta устанавливается так, чтобы соответствовать количеству байт на пиксель в изображении. Например, 24-битное растровое изображение RGB нуждается в dist=3, и также хорошо передать pb=0 в LZMA2, чтобы соответствовать трёхбайтному выравниванию: xz --delta=dist=3 --lzma2=pb=0 foo.tiff Если несколько изображений помещены в один архив (например, .tar), фильтр Delta будет работать на этом тоже, пока все изображения имеют одинаковое количество байт на пиксель. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html>
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Compress or decompress .xz and .lzma files SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz is equivalent to xz --decompress. xzcat is equivalent to xz --decompress --stdout. lzma is equivalent to xz --format=lzma. unlzma is equivalent to xz --format=lzma --decompress. lzcat is equivalent to xz --format=lzma --decompress --stdout. When writing scripts that need to decompress files, it is recommended to always use the name xz with appropriate arguments (xz -d or xz -dc) instead of the names unxz and xzcat. DESCRIPTION xz is a general-purpose data compression tool with command line syntax similar to gzip(1) and bzip2(1). The native file format is the .xz format, but the legacy .lzma format used by LZMA Utils and raw com‐ pressed streams with no container format headers are also supported. In addition, decompression of the .lz format used by lzip is supported. xz compresses or decompresses each file according to the selected oper‐ ation mode. If no files are given or file is -, xz reads from standard input and writes the processed data to standard output. xz will refuse (display an error and skip the file) to write compressed data to stan‐ dard output if it is a terminal. Similarly, xz will refuse to read compressed data from standard input if it is a terminal. Unless --stdout is specified, files other than - are written to a new file whose name is derived from the source file name: • When compressing, the suffix of the target file format (.xz or .lzma) is appended to the source filename to get the target file‐ name. • When decompressing, the .xz, .lzma, or .lz suffix is removed from the filename to get the target filename. xz also recognizes the suffixes .txz and .tlz, and replaces them with the .tar suffix. If the target file already exists, an error is displayed and the file is skipped. Unless writing to standard output, xz will display a warning and skip the file if any of the following applies: • File is not a regular file. Symbolic links are not followed, and thus they are not considered to be regular files. • File has more than one hard link. • File has setuid, setgid, or sticky bit set. • The operation mode is set to compress and the file already has a suffix of the target file format (.xz or .txz when compressing to the .xz format, and .lzma or .tlz when compressing to the .lzma for‐ mat). • The operation mode is set to decompress and the file doesn't have a suffix of any of the supported file formats (.xz, .txz, .lzma, .tlz, or .lz). After successfully compressing or decompressing the file, xz copies the owner, group, permissions, access time, and modification time from the source file to the target file. If copying the group fails, the per‐ missions are modified so that the target file doesn't become accessible to users who didn't have permission to access the source file. xz doesn't support copying other metadata like access control lists or ex‐ tended attributes yet. Once the target file has been successfully closed, the source file is removed unless --keep was specified. The source file is never removed if the output is written to standard output or if an error occurs. Sending SIGINFO or SIGUSR1 to the xz process makes it print progress information to standard error. This has only limited use since when standard error is a terminal, using --verbose will display an automati‐ cally updating progress indicator. Memory usage The memory usage of xz varies from a few hundred kilobytes to several gigabytes depending on the compression settings. The settings used when compressing a file determine the memory requirements of the decom‐ pressor. Typically the decompressor needs 5 % to 20 % of the amount of memory that the compressor needed when creating the file. For example, decompressing a file created with xz -9 currently requires 65 MiB of memory. Still, it is possible to have .xz files that require several gigabytes of memory to decompress. Especially users of older systems may find the possibility of very large memory usage annoying. To prevent uncomfortable surprises, xz has a built-in memory usage limiter, which is disabled by default. While some operating systems provide ways to limit the memory usage of processes, relying on it wasn't deemed to be flexible enough (for exam‐ ple, using ulimit(1) to limit virtual memory tends to cripple mmap(2)). The memory usage limiter can be enabled with the command line option --memlimit=limit. Often it is more convenient to enable the limiter by default by setting the environment variable XZ_DEFAULTS, for example, XZ_DEFAULTS=--memlimit=150MiB. It is possible to set the limits sepa‐ rately for compression and decompression by using --memlimit-com‐ press=limit and --memlimit-decompress=limit. Using these two options outside XZ_DEFAULTS is rarely useful because a single run of xz cannot do both compression and decompression and --memlimit=limit (or -M limit) is shorter to type on the command line. If the specified memory usage limit is exceeded when decompressing, xz will display an error and decompressing the file will fail. If the limit is exceeded when compressing, xz will try to scale the settings down so that the limit is no longer exceeded (except when using --for‐ mat=raw or --no-adjust). This way the operation won't fail unless the limit is very small. The scaling of the settings is done in steps that don't match the compression level presets, for example, if the limit is only slightly less than the amount required for xz -9, the settings will be scaled down only a little, not all the way down to xz -8. Concatenation and padding with .xz files It is possible to concatenate .xz files as is. xz will decompress such files as if they were a single .xz file. It is possible to insert padding between the concatenated parts or af‐ ter the last part. The padding must consist of null bytes and the size of the padding must be a multiple of four bytes. This can be useful, for example, if the .xz file is stored on a medium that measures file sizes in 512-byte blocks. Concatenation and padding are not allowed with .lzma files or raw streams. OPTIONS Integer suffixes and special values In most places where an integer argument is expected, an optional suf‐ fix is supported to easily indicate large integers. There must be no space between the integer and the suffix. KiB Multiply the integer by 1,024 (2^10). Ki, k, kB, K, and KB are accepted as synonyms for KiB. MiB Multiply the integer by 1,048,576 (2^20). Mi, m, M, and MB are accepted as synonyms for MiB. GiB Multiply the integer by 1,073,741,824 (2^30). Gi, g, G, and GB are accepted as synonyms for GiB. The special value max can be used to indicate the maximum integer value supported by the option. Operation mode If multiple operation mode options are given, the last one takes ef‐ fect. -z, --compress Compress. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, unxz implies --decompress). After successful compression, the source file is removed unless writing to standard output or --keep was specified. -d, --decompress, --uncompress Decompress. After successful decompression, the source file is removed unless writing to standard output or --keep was speci‐ fied. -t, --test Test the integrity of compressed files. This option is equiva‐ lent to --decompress --stdout except that the decompressed data is discarded instead of being written to standard output. No files are created or removed. -l, --list Print information about compressed files. No uncompressed out‐ put is produced, and no files are created or removed. In list mode, the program cannot read the compressed data from standard input or from other unseekable sources. The default listing shows basic information about files, one file per line. To get more detailed information, use also the --verbose option. For even more information, use --verbose twice, but note that this may be slow, because getting all the extra information requires many seeks. The width of verbose output exceeds 80 characters, so piping the output to, for exam‐ ple, less -S may be convenient if the terminal isn't wide enough. The exact output may vary between xz versions and different lo‐ cales. For machine-readable output, --robot --list should be used. Operation modifiers -k, --keep Don't delete the input files. Since xz 5.2.6, this option also makes xz compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. In earlier versions this was only done with --force. -f, --force This option has several effects: • If the target file already exists, delete it before compress‐ ing or decompressing. • Compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. • When used with --decompress --stdout and xz cannot recognize the type of the source file, copy the source file as is to standard output. This allows xzcat --force to be used like cat(1) for files that have not been compressed with xz. Note that in future, xz might support new compressed file formats, which may make xz decompress more types of files instead of copying them as is to standard output. --format=format can be used to restrict xz to decompress only a single file for‐ mat. -c, --stdout, --to-stdout Write the compressed or decompressed data to standard output in‐ stead of a file. This implies --keep. --single-stream Decompress only the first .xz stream, and silently ignore possi‐ ble remaining input data following the stream. Normally such trailing garbage makes xz display an error. xz never decompresses more than one stream from .lzma files or raw streams, but this option still makes xz ignore the possible trailing data after the .lzma file or raw stream. This option has no effect if the operation mode is not --decom‐ press or --test. --no-sparse Disable creation of sparse files. By default, if decompressing into a regular file, xz tries to make the file sparse if the de‐ compressed data contains long sequences of binary zeros. It also works when writing to standard output as long as standard output is connected to a regular file and certain additional conditions are met to make it safe. Creating sparse files may save disk space and speed up the decompression by reducing the amount of disk I/O. -S .suf, --suffix=.suf When compressing, use .suf as the suffix for the target file in‐ stead of .xz or .lzma. If not writing to standard output and the source file already has the suffix .suf, a warning is dis‐ played and the file is skipped. When decompressing, recognize files with the suffix .suf in ad‐ dition to files with the .xz, .txz, .lzma, .tlz, or .lz suffix. If the source file has the suffix .suf, the suffix is removed to get the target filename. When compressing or decompressing raw streams (--format=raw), the suffix must always be specified unless writing to standard output, because there is no default suffix for raw streams. --files[=file] Read the filenames to process from file; if file is omitted, filenames are read from standard input. Filenames must be ter‐ minated with the newline character. A dash (-) is taken as a regular filename; it doesn't mean standard input. If filenames are given also as command line arguments, they are processed be‐ fore the filenames read from file. --files0[=file] This is identical to --files[=file] except that each filename must be terminated with the null character. Basic file format and compression options -F format, --format=format Specify the file format to compress or decompress: auto This is the default. When compressing, auto is equiva‐ lent to xz. When decompressing, the format of the input file is automatically detected. Note that raw streams (created with --format=raw) cannot be auto-detected. xz Compress to the .xz file format, or accept only .xz files when decompressing. lzma, alone Compress to the legacy .lzma file format, or accept only .lzma files when decompressing. The alternative name alone is provided for backwards compatibility with LZMA Utils. lzip Accept only .lz files when decompressing. Compression is not supported. The .lz format version 0 and the unextended version 1 are supported. Version 0 files were produced by lzip 1.3 and older. Such files aren't common but may be found from file archives as a few source packages were released in this format. People might have old personal files in this format too. Decompression support for the format version 0 was removed in lzip 1.18. lzip 1.4 and later create files in the format version 1. The sync flush marker extension to the format version 1 was added in lzip 1.6. This extension is rarely used and isn't supported by xz (diagnosed as corrupt input). raw Compress or uncompress a raw stream (no headers). This is meant for advanced users only. To decode raw streams, you need use --format=raw and explicitly specify the fil‐ ter chain, which normally would have been stored in the container headers. -C check, --check=check Specify the type of the integrity check. The check is calcu‐ lated from the uncompressed data and stored in the .xz file. This option has an effect only when compressing into the .xz format; the .lzma format doesn't support integrity checks. The integrity check (if any) is verified when the .xz file is decom‐ pressed. Supported check types: none Don't calculate an integrity check at all. This is usu‐ ally a bad idea. This can be useful when integrity of the data is verified by other means anyway. crc32 Calculate CRC32 using the polynomial from IEEE-802.3 (Ethernet). crc64 Calculate CRC64 using the polynomial from ECMA-182. This is the default, since it is slightly better than CRC32 at detecting damaged files and the speed difference is neg‐ ligible. sha256 Calculate SHA-256. This is somewhat slower than CRC32 and CRC64. Integrity of the .xz headers is always verified with CRC32. It is not possible to change or disable it. --ignore-check Don't verify the integrity check of the compressed data when de‐ compressing. The CRC32 values in the .xz headers will still be verified normally. Do not use this option unless you know what you are doing. Pos‐ sible reasons to use this option: • Trying to recover data from a corrupt .xz file. • Speeding up decompression. This matters mostly with SHA-256 or with files that have compressed extremely well. It's rec‐ ommended to not use this option for this purpose unless the file integrity is verified externally in some other way. -0 ... -9 Select a compression preset level. The default is -6. If mul‐ tiple preset levels are specified, the last one takes effect. If a custom filter chain was already specified, setting a com‐ pression preset level clears the custom filter chain. The differences between the presets are more significant than with gzip(1) and bzip2(1). The selected compression settings determine the memory requirements of the decompressor, thus us‐ ing a too high preset level might make it painful to decompress the file on an old system with little RAM. Specifically, it's not a good idea to blindly use -9 for everything like it often is with gzip(1) and bzip2(1). -0 ... -3 These are somewhat fast presets. -0 is sometimes faster than gzip -9 while compressing much better. The higher ones often have speed comparable to bzip2(1) with compa‐ rable or better compression ratio, although the results depend a lot on the type of data being compressed. -4 ... -6 Good to very good compression while keeping decompressor memory usage reasonable even for old systems. -6 is the default, which is usually a good choice for distributing files that need to be decompressible even on systems with only 16 MiB RAM. (-5e or -6e may be worth considering too. See --extreme.) -7 ... -9 These are like -6 but with higher compressor and decom‐ pressor memory requirements. These are useful only when compressing files bigger than 8 MiB, 16 MiB, and 32 MiB, respectively. On the same hardware, the decompression speed is approximately a constant number of bytes of compressed data per second. In other words, the better the compression, the faster the decom‐ pression will usually be. This also means that the amount of uncompressed output produced per second can vary a lot. The following table summarises the features of the presets: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Column descriptions: • DictSize is the LZMA2 dictionary size. It is waste of memory to use a dictionary bigger than the size of the uncompressed file. This is why it is good to avoid using the presets -7 ... -9 when there's no real need for them. At -6 and lower, the amount of memory wasted is usually low enough to not mat‐ ter. • CompCPU is a simplified representation of the LZMA2 settings that affect compression speed. The dictionary size affects speed too, so while CompCPU is the same for levels -6 ... -9, higher levels still tend to be a little slower. To get even slower and thus possibly better compression, see --extreme. • CompMem contains the compressor memory requirements in the single-threaded mode. It may vary slightly between xz ver‐ sions. • DecMem contains the decompressor memory requirements. That is, the compression settings determine the memory require‐ ments of the decompressor. The exact decompressor memory us‐ age is slightly more than the LZMA2 dictionary size, but the values in the table have been rounded up to the next full MiB. Memory requirements of the multi-threaded mode are significantly higher than that of the single-threaded mode. With the default value of --block-size, each thread needs 3*3*DictSize plus Comp‐ Mem or DecMem. For example, four threads with preset -6 needs 660–670 MiB of memory. -e, --extreme Use a slower variant of the selected compression preset level (-0 ... -9) to hopefully get a little bit better compression ra‐ tio, but with bad luck this can also make it worse. Decompres‐ sor memory usage is not affected, but compressor memory usage increases a little at preset levels -0 ... -3. Since there are two presets with dictionary sizes 4 MiB and 8 MiB, the presets -3e and -5e use slightly faster settings (lower CompCPU) than -4e and -6e, respectively. That way no two presets are identical. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB For example, there are a total of four presets that use 8 MiB dictionary, whose order from the fastest to the slowest is -5, -6, -5e, and -6e. --fast --best These are somewhat misleading aliases for -0 and -9, respec‐ tively. These are provided only for backwards compatibility with LZMA Utils. Avoid using these options. --block-size=size When compressing to the .xz format, split the input data into blocks of size bytes. The blocks are compressed independently from each other, which helps with multi-threading and makes lim‐ ited random-access decompression possible. This option is typi‐ cally used to override the default block size in multi-threaded mode, but this option can be used in single-threaded mode too. In multi-threaded mode about three times size bytes will be al‐ located in each thread for buffering input and output. The de‐ fault size is three times the LZMA2 dictionary size or 1 MiB, whichever is more. Typically a good value is 2–4 times the size of the LZMA2 dictionary or at least 1 MiB. Using size less than the LZMA2 dictionary size is waste of RAM because then the LZMA2 dictionary buffer will never get fully used. In multi-threaded mode, the sizes of the blocks are stored in the block headers. This size information is required for multi-threaded decompres‐ sion. In single-threaded mode no block splitting is done by default. Setting this option doesn't affect memory usage. No size infor‐ mation is stored in block headers, thus files created in single- threaded mode won't be identical to files created in multi- threaded mode. The lack of size information also means that xz won't be able decompress the files in multi-threaded mode. --block-list=items When compressing to the .xz format, start a new block with an optional custom filter chain after the given intervals of uncom‐ pressed data. The items are a comma-separated list. Each item consists of an optional filter chain number between 0 and 9 followed by a colon (:) and a required size of uncompressed data. Omitting an item (two or more consecutive commas) is a shorthand to use the size and filters of the previous item. If the input file is bigger than the sum of the sizes in items, the last item is repeated until the end of the file. A special value of 0 may be used as the last size to indicate that the rest of the file should be encoded as a single block. An alternative filter chain for each block can be specified in combination with the --filters1=filters ... --filters9=filters options. These options define filter chains with an identifier between 1–9. Filter chain 0 can be used to refer to the default filter chain, which is the same as not specifying a filter chain. The filter chain identifier can be used before the un‐ compressed size, followed by a colon (:). For example, if one specifies --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB then blocks will be created using: • The filter chain specified by --filters1 and 2 MiB input • The filter chain specified by --filters3 and 2 MiB input • The filter chain specified by --filters2 and 4 MiB input • The filter chain specified by --filters2 and 4 MiB input • The default filter chain and 2 MiB input • The default filter chain and 4 MiB input for every block un‐ til end of input. If one specifies a size that exceeds the encoder's block size (either the default value in threaded mode or the value speci‐ fied with --block-size=size), the encoder will create additional blocks while keeping the boundaries specified in items. For ex‐ ample, if one specifies --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB and the input file is 80 MiB, one will get 11 blocks: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10, and 1 MiB. In multi-threaded mode the sizes of the blocks are stored in the block headers. This isn't done in single-threaded mode, so the encoded output won't be identical to that of the multi-threaded mode. --flush-timeout=timeout When compressing, if more than timeout milliseconds (a positive integer) has passed since the previous flush and reading more input would block, all the pending input data is flushed from the encoder and made available in the output stream. This can be useful if xz is used to compress data that is streamed over a network. Small timeout values make the data available at the receiving end with a small delay, but large timeout values give better compression ratio. This feature is disabled by default. If this option is speci‐ fied more than once, the last one takes effect. The special timeout value of 0 can be used to explicitly disable this fea‐ ture. This feature is not available on non-POSIX systems. This feature is still experimental. Currently xz is unsuitable for decompressing the stream in real time due to how xz does buffering. --memlimit-compress=limit Set a memory usage limit for compression. If this option is specified multiple times, the last one takes effect. If the compression settings exceed the limit, xz will attempt to adjust the settings downwards so that the limit is no longer ex‐ ceeded and display a notice that automatic adjustment was done. The adjustments are done in this order: reducing the number of threads, switching to single-threaded mode if even one thread in multi-threaded mode exceeds the limit, and finally reducing the LZMA2 dictionary size. When compressing with --format=raw or if --no-adjust has been specified, only the number of threads may be reduced since it can be done without affecting the compressed output. If the limit cannot be met even with the adjustments described above, an error is displayed and xz will exit with exit status 1. The limit can be specified in multiple ways: • The limit can be an absolute value in bytes. Using an inte‐ ger suffix like MiB can be useful. Example: --memlimit-com‐ press=80MiB • The limit can be specified as a percentage of total physical memory (RAM). This can be useful especially when setting the XZ_DEFAULTS environment variable in a shell initialization script that is shared between different computers. That way the limit is automatically bigger on systems with more mem‐ ory. Example: --memlimit-compress=70% • The limit can be reset back to its default value by setting it to 0. This is currently equivalent to setting the limit to max (no memory usage limit). For 32-bit xz there is a special case: if the limit would be over 4020 MiB, the limit is set to 4020 MiB. On MIPS32 2000 MiB is used instead. (The values 0 and max aren't affected by this. A similar feature doesn't exist for decompression.) This can be helpful when a 32-bit executable has access to 4 GiB address space (2 GiB on MIPS32) while hopefully doing no harm in other situations. See also the section Memory usage. --memlimit-decompress=limit Set a memory usage limit for decompression. This also affects the --list mode. If the operation is not possible without ex‐ ceeding the limit, xz will display an error and decompressing the file will fail. See --memlimit-compress=limit for possible ways to specify the limit. --memlimit-mt-decompress=limit Set a memory usage limit for multi-threaded decompression. This can only affect the number of threads; this will never make xz refuse to decompress a file. If limit is too low to allow any multi-threading, the limit is ignored and xz will continue in single-threaded mode. Note that if also --memlimit-decompress is used, it will always apply to both single-threaded and multi- threaded modes, and so the effective limit for multi-threading will never be higher than the limit set with --memlimit-decom‐ press. In contrast to the other memory usage limit options, --mem‐ limit-mt-decompress=limit has a system-specific default limit. xz --info-memory can be used to see the current value. This option and its default value exist because without any limit the threaded decompressor could end up allocating an in‐ sane amount of memory with some input files. If the default limit is too low on your system, feel free to increase the limit but never set it to a value larger than the amount of usable RAM as with appropriate input files xz will attempt to use that amount of memory even with a low number of threads. Running out of memory or swapping will not improve decompression perfor‐ mance. See --memlimit-compress=limit for possible ways to specify the limit. Setting limit to 0 resets the limit to the default sys‐ tem-specific value. -M limit, --memlimit=limit, --memory=limit This is equivalent to specifying --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Display an error and exit if the memory usage limit cannot be met without adjusting settings that affect the compressed out‐ put. That is, this prevents xz from switching the encoder from multi-threaded mode to single-threaded mode and from reducing the LZMA2 dictionary size. Even when this option is used the number of threads may be reduced to meet the memory usage limit as that won't affect the compressed output. Automatic adjusting is always disabled when creating raw streams (--format=raw). -T threads, --threads=threads Specify the number of worker threads to use. Setting threads to a special value 0 makes xz use up to as many threads as the pro‐ cessor(s) on the system support. The actual number of threads can be fewer than threads if the input file is not big enough for threading with the given settings or if using more threads would exceed the memory usage limit. The single-threaded and multi-threaded compressors produce dif‐ ferent output. Single-threaded compressor will give the small‐ est file size but only the output from the multi-threaded com‐ pressor can be decompressed using multiple threads. Setting threads to 1 will use the single-threaded mode. Setting threads to any other value, including 0, will use the multi-threaded compressor even if the system supports only one hardware thread. (xz 5.2.x used single-threaded mode in this situation.) To use multi-threaded mode with only one thread, set threads to +1. The + prefix has no effect with values other than 1. A memory usage limit can still make xz switch to single-threaded mode unless --no-adjust is used. Support for the + prefix was added in xz 5.4.0. If an automatic number of threads has been requested and no mem‐ ory usage limit has been specified, then a system-specific de‐ fault soft limit will be used to possibly limit the number of threads. It is a soft limit in sense that it is ignored if the number of threads becomes one, thus a soft limit will never stop xz from compressing or decompressing. This default soft limit will not make xz switch from multi-threaded mode to single- threaded mode. The active limits can be seen with xz --info-memory. Currently the only threading method is to split the input into blocks and compress them independently from each other. The de‐ fault block size depends on the compression level and can be overridden with the --block-size=size option. Threaded decompression only works on files that contain multiple blocks with size information in block headers. All large enough files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size has been used. The default value for threads is 0. In xz 5.4.x and older the default is 1. Custom compressor filter chains A custom filter chain allows specifying the compression settings in de‐ tail instead of relying on the settings associated to the presets. When a custom filter chain is specified, preset options (-0 ... -9 and --extreme) earlier on the command line are forgotten. If a preset op‐ tion is specified after one or more custom filter chain options, the new preset takes effect and the custom filter chain options specified earlier are forgotten. A filter chain is comparable to piping on the command line. When com‐ pressing, the uncompressed input goes to the first filter, whose output goes to the next filter (if any). The output of the last filter gets written to the compressed file. The maximum number of filters in the chain is four, but typically a filter chain has only one or two fil‐ ters. Many filters have limitations on where they can be in the filter chain: some filters can work only as the last filter in the chain, some only as a non-last filter, and some work in any position in the chain. De‐ pending on the filter, this limitation is either inherent to the filter design or exists to prevent security issues. A custom filter chain can be specified in two different ways. The op‐ tions --filters=filters and --filters1=filters ... --filters9=filters allow specifying an entire filter chain in one option using the liblzma filter string syntax. Alternatively, a filter chain can be specified by using one or more individual filter options in the order they are wanted in the filter chain. That is, the order of the individual fil‐ ter options is significant! When decoding raw streams (--format=raw), the filter chain must be specified in the same order as it was speci‐ fied when compressing. Any individual filter or preset options speci‐ fied before the full chain option (--filters=filters) will be forgot‐ ten. Individual filters specified after the full chain option will re‐ set the filter chain. Both the full and individual filter options take filter-specific op‐ tions as a comma-separated list. Extra commas in options are ignored. Every option has a default value, so specify those you want to change. To see the whole filter chain and options, use xz -vv (that is, use --verbose twice). This works also for viewing the filter chain options used by presets. --filters=filters Specify the full filter chain or a preset in a single option. Each filter can be separated by spaces or two dashes (--). fil‐ ters may need to be quoted on the shell command line so it is parsed as a single option. To denote options, use : or =. A preset can be prefixed with a - and followed with zero or more flags. The only supported flag is e to apply the same options as --extreme. --filters1=filters ... --filters9=filters Specify up to nine additional filter chains that can be used with --block-list. For example, when compressing an archive with executable files followed by text files, the executable part could use a filter chain with a BCJ filter and the text part only the LZMA2 filter. --filters-help Display a help message describing how to specify presets and custom filter chains in the --filters and --filters1=filters ... --filters9=filters options, and exit successfully. --lzma1[=options] --lzma2[=options] Add LZMA1 or LZMA2 filter to the filter chain. These filters can be used only as the last filter in the chain. LZMA1 is a legacy filter, which is supported almost solely due to the legacy .lzma file format, which supports only LZMA1. LZMA2 is an updated version of LZMA1 to fix some practical is‐ sues of LZMA1. The .xz format uses LZMA2 and doesn't support LZMA1 at all. Compression speed and ratios of LZMA1 and LZMA2 are practically the same. LZMA1 and LZMA2 share the same set of options: preset=preset Reset all LZMA1 or LZMA2 options to preset. Preset con‐ sist of an integer, which may be followed by single-let‐ ter preset modifiers. The integer can be from 0 to 9, matching the command line options -0 ... -9. The only supported modifier is currently e, which matches --ex‐ treme. If no preset is specified, the default values of LZMA1 or LZMA2 options are taken from the preset 6. dict=size Dictionary (history buffer) size indicates how many bytes of the recently processed uncompressed data is kept in memory. The algorithm tries to find repeating byte se‐ quences (matches) in the uncompressed data, and replace them with references to the data currently in the dictio‐ nary. The bigger the dictionary, the higher is the chance to find a match. Thus, increasing dictionary size usually improves compression ratio, but a dictionary big‐ ger than the uncompressed file is waste of memory. Typical dictionary size is from 64 KiB to 64 MiB. The minimum is 4 KiB. The maximum for compression is cur‐ rently 1.5 GiB (1536 MiB). The decompressor already sup‐ ports dictionaries up to one byte less than 4 GiB, which is the maximum for the LZMA1 and LZMA2 stream formats. Dictionary size and match finder (mf) together determine the memory usage of the LZMA1 or LZMA2 encoder. The same (or bigger) dictionary size is required for decompressing that was used when compressing, thus the memory usage of the decoder is determined by the dictionary size used when compressing. The .xz headers store the dictionary size either as 2^n or 2^n + 2^(n-1), so these sizes are somewhat preferred for compression. Other sizes will get rounded up when stored in the .xz headers. lc=lc Specify the number of literal context bits. The minimum is 0 and the maximum is 4; the default is 3. In addi‐ tion, the sum of lc and lp must not exceed 4. All bytes that cannot be encoded as matches are encoded as literals. That is, literals are simply 8-bit bytes that are encoded one at a time. The literal coding makes an assumption that the highest lc bits of the previous uncompressed byte correlate with the next byte. For example, in typical English text, an upper-case letter is often followed by a lower-case let‐ ter, and a lower-case letter is usually followed by an‐ other lower-case letter. In the US-ASCII character set, the highest three bits are 010 for upper-case letters and 011 for lower-case letters. When lc is at least 3, the literal coding can take advantage of this property in the uncompressed data. The default value (3) is usually good. If you want maxi‐ mum compression, test lc=4. Sometimes it helps a little, and sometimes it makes compression worse. If it makes it worse, test lc=2 too. lp=lp Specify the number of literal position bits. The minimum is 0 and the maximum is 4; the default is 0. Lp affects what kind of alignment in the uncompressed data is assumed when encoding literals. See pb below for more information about alignment. pb=pb Specify the number of position bits. The minimum is 0 and the maximum is 4; the default is 2. Pb affects what kind of alignment in the uncompressed data is assumed in general. The default means four-byte alignment (2^pb=2^2=4), which is often a good choice when there's no better guess. When the alignment is known, setting pb accordingly may reduce the file size a little. For example, with text files having one-byte alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can improve compression slightly. For UTF-16 text, pb=1 is a good choice. If the alignment is an odd number like 3 bytes, pb=0 might be the best choice. Even though the assumed alignment can be adjusted with pb and lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment. It might be worth taking into account when designing file formats that are likely to be often com‐ pressed with LZMA1 or LZMA2. mf=mf Match finder has a major effect on encoder speed, memory usage, and compression ratio. Usually Hash Chain match finders are faster than Binary Tree match finders. The default depends on the preset: 0 uses hc3, 1–3 use hc4, and the rest use bt4. The following match finders are supported. The memory usage formulas below are rough approximations, which are closest to the reality when dict is a power of two. hc3 Hash Chain with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 7.5 (if dict <= 16 MiB); dict * 5.5 + 64 MiB (if dict > 16 MiB) hc4 Hash Chain with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 7.5 (if dict <= 32 MiB); dict * 6.5 (if dict > 32 MiB) bt2 Binary Tree with 2-byte hashing Minimum value for nice: 2 Memory usage: dict * 9.5 bt3 Binary Tree with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 11.5 (if dict <= 16 MiB); dict * 9.5 + 64 MiB (if dict > 16 MiB) bt4 Binary Tree with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 11.5 (if dict <= 32 MiB); dict * 10.5 (if dict > 32 MiB) mode=mode Compression mode specifies the method to analyze the data produced by the match finder. Supported modes are fast and normal. The default is fast for presets 0–3 and nor‐ mal for presets 4–9. Usually fast is used with Hash Chain match finders and normal with Binary Tree match finders. This is also what the presets do. nice=nice Specify what is considered to be a nice length for a match. Once a match of at least nice bytes is found, the algorithm stops looking for possibly better matches. Nice can be 2–273 bytes. Higher values tend to give bet‐ ter compression ratio at the expense of speed. The de‐ fault depends on the preset. depth=depth Specify the maximum search depth in the match finder. The default is the special value of 0, which makes the compressor determine a reasonable depth from mf and nice. Reasonable depth for Hash Chains is 4–100 and 16–1000 for Binary Trees. Using very high values for depth can make the encoder extremely slow with some files. Avoid set‐ ting the depth over 1000 unless you are prepared to in‐ terrupt the compression in case it is taking far too long. When decoding raw streams (--format=raw), LZMA2 needs only the dictionary size. LZMA1 needs also lc, lp, and pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Add a branch/call/jump (BCJ) filter to the filter chain. These filters can be used only as a non-last filter in the filter chain. A BCJ filter converts relative addresses in the machine code to their absolute counterparts. This doesn't change the size of the data but it increases redundancy, which can help LZMA2 to produce 0–15 % smaller .xz file. The BCJ filters are always re‐ versible, so using a BCJ filter for wrong type of data doesn't cause any data loss, although it may make the compression ratio slightly worse. The BCJ filters are very fast and use an in‐ significant amount of memory. These BCJ filters have known problems related to the compression ratio: • Some types of files containing executable code (for example, object files, static libraries, and Linux kernel modules) have the addresses in the instructions filled with filler values. These BCJ filters will still do the address conver‐ sion, which will make the compression worse with these files. • If a BCJ filter is applied on an archive, it is possible that it makes the compression ratio worse than not using a BCJ filter. For example, if there are similar or even identical executables then filtering will likely make the files less similar and thus compression is worse. The contents of non- executable files in the same archive can matter too. In practice one has to try with and without a BCJ filter to see which is better in each situation. Different instruction sets have different alignment: the exe‐ cutable file must be aligned to a multiple of this value in the input data to make the filter work. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit or 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Since the BCJ-filtered data is usually compressed with LZMA2, the compression ratio may be improved slightly if the LZMA2 op‐ tions are set to match the alignment of the selected BCJ filter. Examples: • IA-64 filter has 16-byte alignment so pb=4,lp=4,lc=0 is good with LZMA2 (2^4=16). • RISC-V code has 2-byte or 4-byte alignment depending on whether the file contains 16-bit compressed instructions (the C extension). When 16-bit instructions are used, pb=2,lp=1,lc=3 or pb=1,lp=1,lc=3 is good. When 16-bit in‐ structions aren't present, pb=2,lp=2,lc=2 is the best. read‐ elf -h can be used to check if "RVC" appears on the "Flags" line. • ARM64 is always 4-byte aligned so pb=2,lp=2,lc=2 is the best. • The x86 filter is an exception. It's usually good to stick to LZMA2's defaults (pb=2,lp=0,lc=3) when compressing x86 ex‐ ecutables. All BCJ filters support the same options: start=offset Specify the start offset that is used when converting be‐ tween relative and absolute addresses. The offset must be a multiple of the alignment of the filter (see the ta‐ ble above). The default is zero. In practice, the de‐ fault is good; specifying a custom offset is almost never useful. --delta[=options] Add the Delta filter to the filter chain. The Delta filter can be only used as a non-last filter in the filter chain. Currently only simple byte-wise delta calculation is supported. It can be useful when compressing, for example, uncompressed bitmap images or uncompressed PCM audio. However, special pur‐ pose algorithms may give significantly better results than Delta + LZMA2. This is true especially with audio, which compresses faster and better, for example, with flac(1). Supported options: dist=distance Specify the distance of the delta calculation in bytes. distance must be 1–256. The default is 1. For example, with dist=2 and eight-byte input A1 B1 A2 B3 A3 B5 A4 B7, the output will be A1 B1 01 02 01 02 01 02. Other options -q, --quiet Suppress warnings and notices. Specify this twice to suppress errors too. This option has no effect on the exit status. That is, even if a warning was suppressed, the exit status to indi‐ cate a warning is still used. -v, --verbose Be verbose. If standard error is connected to a terminal, xz will display a progress indicator. Specifying --verbose twice will give even more verbose output. The progress indicator shows the following information: • Completion percentage is shown if the size of the input file is known. That is, the percentage cannot be shown in pipes. • Amount of compressed data produced (compressing) or consumed (decompressing). • Amount of uncompressed data consumed (compressing) or pro‐ duced (decompressing). • Compression ratio, which is calculated by dividing the amount of compressed data processed so far by the amount of uncom‐ pressed data processed so far. • Compression or decompression speed. This is measured as the amount of uncompressed data consumed (compression) or pro‐ duced (decompression) per second. It is shown after a few seconds have passed since xz started processing the file. • Elapsed time in the format M:SS or H:MM:SS. • Estimated remaining time is shown only when the size of the input file is known and a couple of seconds have already passed since xz started processing the file. The time is shown in a less precise format which never has any colons, for example, 2 min 30 s. When standard error is not a terminal, --verbose will make xz print the filename, compressed size, uncompressed size, compres‐ sion ratio, and possibly also the speed and elapsed time on a single line to standard error after compressing or decompressing the file. The speed and elapsed time are included only when the operation took at least a few seconds. If the operation didn't finish, for example, due to user interruption, also the comple‐ tion percentage is printed if the size of the input file is known. -Q, --no-warn Don't set the exit status to 2 even if a condition worth a warn‐ ing was detected. This option doesn't affect the verbosity level, thus both --quiet and --no-warn have to be used to not display warnings and to not alter the exit status. --robot Print messages in a machine-parsable format. This is intended to ease writing frontends that want to use xz instead of li‐ blzma, which may be the case with various scripts. The output with this option enabled is meant to be stable across xz re‐ leases. See the section ROBOT MODE for details. --info-memory Display, in human-readable format, how much physical memory (RAM) and how many processor threads xz thinks the system has and the memory usage limits for compression and decompression, and exit successfully. -h, --help Display a help message describing the most commonly used op‐ tions, and exit successfully. -H, --long-help Display a help message describing all features of xz, and exit successfully -V, --version Display the version number of xz and liblzma in human readable format. To get machine-parsable output, specify --robot before --version. ROBOT MODE The robot mode is activated with the --robot option. It makes the out‐ put of xz easier to parse by other programs. Currently --robot is sup‐ ported only together with --list, --filters-help, --info-memory, and --version. It will be supported for compression and decompression in the future. List mode xz --robot --list uses tab-separated output. The first column of every line has a string that indicates the type of the information found on that line: name This is always the first line when starting to list a file. The second column on the line is the filename. file This line contains overall information about the .xz file. This line is always printed after the name line. stream This line type is used only when --verbose was specified. There are as many stream lines as there are streams in the .xz file. block This line type is used only when --verbose was specified. There are as many block lines as there are blocks in the .xz file. The block lines are shown after all the stream lines; different line types are not interleaved. summary This line type is used only when --verbose was specified twice. This line is printed after all block lines. Like the file line, the summary line contains overall information about the .xz file. totals This line is always the very last line of the list output. It shows the total counts and sizes. The columns of the file lines: 2. Number of streams in the file 3. Total number of blocks in the stream(s) 4. Compressed size of the file 5. Uncompressed size of the file 6. Compression ratio, for example, 0.123. If ratio is over 9.999, three dashes (---) are displayed instead of the ra‐ tio. 7. Comma-separated list of integrity check names. The follow‐ ing strings are used for the known check types: None, CRC32, CRC64, and SHA-256. For unknown check types, Unknown-N is used, where N is the Check ID as a decimal number (one or two digits). 8. Total size of stream padding in the file The columns of the stream lines: 2. Stream number (the first stream is 1) 3. Number of blocks in the stream 4. Compressed start offset 5. Uncompressed start offset 6. Compressed size (does not include stream padding) 7. Uncompressed size 8. Compression ratio 9. Name of the integrity check 10. Size of stream padding The columns of the block lines: 2. Number of the stream containing this block 3. Block number relative to the beginning of the stream (the first block is 1) 4. Block number relative to the beginning of the file 5. Compressed start offset relative to the beginning of the file 6. Uncompressed start offset relative to the beginning of the file 7. Total compressed size of the block (includes headers) 8. Uncompressed size 9. Compression ratio 10. Name of the integrity check If --verbose was specified twice, additional columns are included on the block lines. These are not displayed with a single --verbose, be‐ cause getting this information requires many seeks and can thus be slow: 11. Value of the integrity check in hexadecimal 12. Block header size 13. Block flags: c indicates that compressed size is present, and u indicates that uncompressed size is present. If the flag is not set, a dash (-) is shown instead to keep the string length fixed. New flags may be added to the end of the string in the future. 14. Size of the actual compressed data in the block (this ex‐ cludes the block header, block padding, and check fields) 15. Amount of memory (in bytes) required to decompress this block with this xz version 16. Filter chain. Note that most of the options used at com‐ pression time cannot be known, because only the options that are needed for decompression are stored in the .xz headers. The columns of the summary lines: 2. Amount of memory (in bytes) required to decompress this file with this xz version 3. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 4. Minimum xz version required to decompress the file The columns of the totals line: 2. Number of streams 3. Number of blocks 4. Compressed size 5. Uncompressed size 6. Average compression ratio 7. Comma-separated list of integrity check names that were present in the files 8. Stream padding size 9. Number of files. This is here to keep the order of the ear‐ lier columns the same as on file lines. If --verbose was specified twice, additional columns are included on the totals line: 10. Maximum amount of memory (in bytes) required to decompress the files with this xz version 11. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 12. Minimum xz version required to decompress the file Future versions may add new line types and new columns can be added to the existing line types, but the existing columns won't be changed. Filters help xz --robot --filters-help prints the supported filters in the following format: filter:option=<value>,option=<value>... filter Name of the filter option Name of a filter specific option value Numeric value ranges appear as <min-max>. String value choices are shown within < > and separated by a | character. Each filter is printed on its own line. Memory limit information xz --robot --info-memory prints a single line with multiple tab-sepa‐ rated columns: 1. Total amount of physical memory (RAM) in bytes. 2. Memory usage limit for compression in bytes (--memlimit-compress). A special value of 0 indicates the default setting which for sin‐ gle-threaded mode is the same as no limit. 3. Memory usage limit for decompression in bytes (--memlimit-decom‐ press). A special value of 0 indicates the default setting which for single-threaded mode is the same as no limit. 4. Since xz 5.3.4alpha: Memory usage for multi-threaded decompression in bytes (--memlimit-mt-decompress). This is never zero because a system-specific default value shown in the column 5 is used if no limit has been specified explicitly. This is also never greater than the value in the column 3 even if a larger value has been specified with --memlimit-mt-decompress. 5. Since xz 5.3.4alpha: A system-specific default memory usage limit that is used to limit the number of threads when compressing with an automatic number of threads (--threads=0) and no memory usage limit has been specified (--memlimit-compress). This is also used as the default value for --memlimit-mt-decompress. 6. Since xz 5.3.4alpha: Number of available processor threads. In the future, the output of xz --robot --info-memory may have more columns, but never more than a single line. Version xz --robot --version prints the version number of xz and liblzma in the following format: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Major version. YYY Minor version. Even numbers are stable. Odd numbers are alpha or beta versions. ZZZ Patch level for stable releases or just a counter for develop‐ ment releases. S Stability. 0 is alpha, 1 is beta, and 2 is stable. S should be always 2 when YYY is even. XYYYZZZS are the same on both lines if xz and liblzma are from the same XZ Utils release. Examples: 4.999.9beta is 49990091 and 5.0.0 is 50000002. EXIT STATUS 0 All is good. 1 An error occurred. 2 Something worth a warning occurred, but no actual errors oc‐ curred. Notices (not warnings or errors) printed on standard error don't affect the exit status. ENVIRONMENT xz parses space-separated lists of options from the environment vari‐ ables XZ_DEFAULTS and XZ_OPT, in this order, before parsing the options from the command line. Note that only options are parsed from the en‐ vironment variables; all non-options are silently ignored. Parsing is done with getopt_long(3) which is used also for the command line argu‐ ments. XZ_DEFAULTS User-specific or system-wide default options. Typically this is set in a shell initialization script to enable xz's memory usage limiter by default. Excluding shell initialization scripts and similar special cases, scripts must never set or unset XZ_DE‐ FAULTS. XZ_OPT This is for passing options to xz when it is not possible to set the options directly on the xz command line. This is the case when xz is run by a script or tool, for example, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Scripts may use XZ_OPT, for example, to set script-specific de‐ fault compression options. It is still recommended to allow users to override XZ_OPT if that is reasonable. For example, in sh(1) scripts one may use something like this: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY The command line syntax of xz is practically a superset of lzma, un‐ lzma, and lzcat as found from LZMA Utils 4.32.x. In most cases, it is possible to replace LZMA Utils with XZ Utils without breaking existing scripts. There are some incompatibilities though, which may sometimes cause problems. Compression preset levels The numbering of the compression level presets is not identical in xz and LZMA Utils. The most important difference is how dictionary sizes are mapped to different presets. Dictionary size is roughly equal to the decompressor memory usage. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB The dictionary size differences affect the compressor memory usage too, but there are some other differences between LZMA Utils and XZ Utils, which make the difference even bigger: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB The default preset level in LZMA Utils is -7 while in XZ Utils it is -6, so both use an 8 MiB dictionary by default. Streamed vs. non-streamed .lzma files The uncompressed size of the file can be stored in the .lzma header. LZMA Utils does that when compressing regular files. The alternative is to mark that uncompressed size is unknown and use end-of-payload marker to indicate where the decompressor should stop. LZMA Utils uses this method when uncompressed size isn't known, which is the case, for example, in pipes. xz supports decompressing .lzma files with or without end-of-payload marker, but all .lzma files created by xz will use end-of-payload marker and have uncompressed size marked as unknown in the .lzma header. This may be a problem in some uncommon situations. For exam‐ ple, a .lzma decompressor in an embedded device might work only with files that have known uncompressed size. If you hit this problem, you need to use LZMA Utils or LZMA SDK to create .lzma files with known un‐ compressed size. Unsupported .lzma files The .lzma format allows lc values up to 8, and lp values up to 4. LZMA Utils can decompress files with any lc and lp, but always creates files with lc=3 and lp=0. Creating files with other lc and lp is possible with xz and with LZMA SDK. The implementation of the LZMA1 filter in liblzma requires that the sum of lc and lp must not exceed 4. Thus, .lzma files, which exceed this limitation, cannot be decompressed with xz. LZMA Utils creates only .lzma files which have a dictionary size of 2^n (a power of 2) but accepts files with any dictionary size. liblzma ac‐ cepts only .lzma files which have a dictionary size of 2^n or 2^n + 2^(n-1). This is to decrease false positives when detecting .lzma files. These limitations shouldn't be a problem in practice, since practically all .lzma files have been compressed with settings that liblzma will accept. Trailing garbage When decompressing, LZMA Utils silently ignore everything after the first .lzma stream. In most situations, this is a bug. This also means that LZMA Utils don't support decompressing concatenated .lzma files. If there is data left after the first .lzma stream, xz considers the file to be corrupt unless --single-stream was used. This may break ob‐ scure scripts which have assumed that trailing garbage is ignored. NOTES Compressed output may vary The exact compressed output produced from the same uncompressed input file may vary between XZ Utils versions even if compression options are identical. This is because the encoder can be improved (faster or bet‐ ter compression) without affecting the file format. The output can vary even between different builds of the same XZ Utils version, if different build options are used. The above means that once --rsyncable has been implemented, the result‐ ing files won't necessarily be rsyncable unless both old and new files have been compressed with the same xz version. This problem can be fixed if a part of the encoder implementation is frozen to keep rsynca‐ ble output stable across xz versions. Embedded .xz decompressors Embedded .xz decompressor implementations like XZ Embedded don't neces‐ sarily support files created with integrity check types other than none and crc32. Since the default is --check=crc64, you must use --check=none or --check=crc32 when creating files for embedded systems. Outside embedded systems, all .xz format decompressors support all the check types, or at least are able to decompress the file without veri‐ fying the integrity check if the particular check is not supported. XZ Embedded supports BCJ filters, but only with the default start off‐ set. EXAMPLES Basics Compress the file foo into foo.xz using the default compression level (-6), and remove foo if compression is successful: xz foo Decompress bar.xz into bar and don't remove bar.xz even if decompres‐ sion is successful: xz -dk bar.xz Create baz.tar.xz with the preset -4e (-4 --extreme), which is slower than the default -6, but needs less memory for compression and decom‐ pression (48 MiB and 5 MiB, respectively): tar cf - baz | xz -4e > baz.tar.xz A mix of compressed and uncompressed files can be decompressed to stan‐ dard output with a single command: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Parallel compression of many files On GNU and *BSD, find(1) and xargs(1) can be used to parallelize com‐ pression of many files: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 The -P option to xargs(1) sets the number of parallel xz processes. The best value for the -n option depends on how many files there are to be compressed. If there are only a couple of files, the value should probably be 1; with tens of thousands of files, 100 or even more may be appropriate to reduce the number of xz processes that xargs(1) will eventually create. The option -T1 for xz is there to force it to single-threaded mode, be‐ cause xargs(1) is used to control the amount of parallelization. Robot mode Calculate how many bytes have been saved in total after compressing multiple files: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' A script may want to know that it is using new enough xz. The follow‐ ing sh(1) script checks that the version number of the xz tool is at least 5.0.0. This method is compatible with old beta versions, which didn't support the --robot option: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Set a memory usage limit for decompression using XZ_OPT, but if a limit has already been set, don't increase it: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Custom compressor filter chains The simplest use for custom filter chains is customizing a LZMA2 pre‐ set. This can be useful, because the presets cover only a subset of the potentially useful combinations of compression settings. The CompCPU columns of the tables from the descriptions of the options -0 ... -9 and --extreme are useful when customizing LZMA2 presets. Here are the relevant parts collected from those two tables: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 If you know that a file requires somewhat big dictionary (for example, 32 MiB) to compress well, but you want to compress it quicker than xz -8 would do, a preset with a low CompCPU value (for example, 1) can be modified to use a bigger dictionary: xz --lzma2=preset=1,dict=32MiB foo.tar With certain files, the above command may be faster than xz -6 while compressing significantly better. However, it must be emphasized that only some files benefit from a big dictionary while keeping the CompCPU value low. The most obvious situation, where a big dictionary can help a lot, is an archive containing very similar files of at least a few megabytes each. The dictionary size has to be significantly bigger than any individual file to allow LZMA2 to take full advantage of the similarities between consecutive files. If very high compressor and decompressor memory usage is fine, and the file being compressed is at least several hundred megabytes, it may be useful to use an even bigger dictionary than the 64 MiB that xz -9 would use: xz -vv --lzma2=dict=192MiB big_foo.tar Using -vv (--verbose --verbose) like in the above example can be useful to see the memory requirements of the compressor and decompressor. Re‐ member that using a dictionary bigger than the size of the uncompressed file is waste of memory, so the above command isn't useful for small files. Sometimes the compression time doesn't matter, but the decompressor memory usage has to be kept low, for example, to make it possible to decompress the file on an embedded system. The following command uses -6e (-6 --extreme) as a base and sets the dictionary to only 64 KiB. The resulting file can be decompressed with XZ Embedded (that's why there is --check=crc32) using about 100 KiB of memory. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo If you want to squeeze out as many bytes as possible, adjusting the number of literal context bits (lc) and number of position bits (pb) can sometimes help. Adjusting the number of literal position bits (lp) might help too, but usually lc and pb are more important. For example, a source code archive contains mostly US-ASCII text, so something like the following might give slightly (like 0.1 %) smaller file than xz -6e (try also without lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Using another filter together with LZMA2 can improve compression with certain file types. For example, to compress a x86-32 or x86-64 shared library using the x86 BCJ filter: xz --x86 --lzma2 libfoo.so Note that the order of the filter options is significant. If --x86 is specified after --lzma2, xz will give an error, because there cannot be any filter after LZMA2, and also because the x86 BCJ filter cannot be used as the last filter in the chain. The Delta filter together with LZMA2 can give good results with bitmap images. It should usually beat PNG, which has a few more advanced fil‐ ters than simple delta but uses Deflate for the actual compression. The image has to be saved in uncompressed format, for example, as un‐ compressed TIFF. The distance parameter of the Delta filter is set to match the number of bytes per pixel in the image. For example, 24-bit RGB bitmap needs dist=3, and it is also good to pass pb=0 to LZMA2 to accommodate the three-byte alignment: xz --delta=dist=3 --lzma2=pb=0 foo.tiff If multiple images have been put into a single archive (for example, .tar), the Delta filter will work on that too as long as all images have the same number of bytes per pixel. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html> Tukaani 2024-12-30 XZ(1)
XZLESS(1) XZ Utils XZLESS(1) NAME xzless, lzless - просмотр сжатых файлов xz или lzma (текстовых) SYNOPSIS xzless [file...] lzless [file...] DESCRIPTION xzless — это фильтр, который отображает текст из сжатых файлов в терми‐ нал. Файлы, поддерживаемые xz(1), распаковываются; другие файлы пред‐ полагаются не сжатыми. Если файлы не указаны, xzless читает из стан‐ дартного ввода. xzless использует less(1) для вывода. В отличие от xzmore, выбор про‐ сматриватель не может быть изменён с помощью переменной окружения. Команды основаны на both more(1) и vi(1) и позволяют перемещаться вперёд и на‐ зад, а также выполнять поиск. Смотрите руководство less(1) для дополни‐ тельной информации. Команда lzless предоставлена для обратной совместимости с LZMA Utils. ENVIRONMENT LESSMETACHARS Список символов, специальных для оболочки. Устанавливается xzless, если он ещё не задан в окружении. LESSOPEN Устанавливается в командную строку для вызова декомпрессора xz(1) для предварительной обработки входных файлов для less(1). SEE ALSO less(1), xz(1), xzmore(1), zless(1) Tukaani 2024-02-12 XZLESS(1)
XZLESS(1) XZ Utils XZLESS(1) NAME xzless, lzless - view xz or lzma compressed (text) files SYNOPSIS xzless [file...] lzless [file...] DESCRIPTION xzless is a filter that displays text from compressed files to a termi‐ nal. Files supported by xz(1) are decompressed; other files are as‐ sumed to be in uncompressed form already. If no files are given, xz‐ less reads from standard input. xzless uses less(1) to present its output. Unlike xzmore, its choice of pager cannot be altered by setting an environment variable. Com‐ mands are based on both more(1) and vi(1) and allow back and forth movement and searching. See the less(1) manual for more information. The command named lzless is provided for backward compatibility with LZMA Utils. ENVIRONMENT LESSMETACHARS A list of characters special to the shell. Set by xzless unless it is already set in the environment. LESSOPEN Set to a command line to invoke the xz(1) decompressor for pre‐ processing the input files to less(1). SEE ALSO less(1), xz(1), xzmore(1), zless(1) Tukaani 2024-02-12 XZLESS(1)
XZMORE(1) XZ Utils XZMORE(1) NAME xzmore, lzmore - просмотр сжатых xz или lzma (текстовых) файлов SYNOPSIS xzmore [file...] lzmore [file...] DESCRIPTION xzmore отображает текст из сжатых файлов на терминале с помощью more(1). Файлы, поддерживаемые xz(1), разархивируются; другие файлы предполагаются уже несжатыми. Если файлы не указаны, xzmore читает из стандартного ввода. См. руководство more(1) для команд клавиатуры. Обратите внимание, что прокрутка назад может быть невозможной в зависимости от реализации more(1). Это происходит потому, что xzmore использует pipe для передачи разархивированных данных more(1). xzless(1) использует less(1), который предоставляет более продвинутые функции. Команда lzmore предоставлена для обеспечения обратной совместимости с LZMA Utils. ENVIRONMENT PAGER Если PAGER установлен, его значение используется в качестве пейджера вместо more(1). SEE ALSO more(1), xz(1), xzless(1), zmore(1) Tukaani 2024-02-12 XZMORE(1)
XZMORE(1) XZ Utils XZMORE(1) NAME xzmore, lzmore - view xz or lzma compressed (text) files SYNOPSIS xzmore [file...] lzmore [file...] DESCRIPTION xzmore displays text from compressed files to a terminal using more(1). Files supported by xz(1) are decompressed; other files are assumed to be in uncompressed form already. If no files are given, xzmore reads from standard input. See the more(1) manual for the keyboard commands. Note that scrolling backwards might not be possible depending on the implementation of more(1). This is because xzmore uses a pipe to pass the decompressed data to more(1). xzless(1) uses less(1) which pro‐ vides more advanced features. The command lzmore is provided for backward compatibility with LZMA Utils. ENVIRONMENT PAGER If PAGER is set, its value is used as the pager instead of more(1). SEE ALSO more(1), xz(1), xzless(1), zmore(1) Tukaani 2024-02-12 XZMORE(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - поиск шаблонов в возможно сжатых файлах SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep вызывает grep(1) для не сжатого содержимого файлов. Форматы файлов определяются по суффиксам имён файлов. Любой файл с суффиксом, поддерживаемым xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1), будет разархивирован; все остальные файлы предполагаются не сжатыми. Если файлы не указаны или файл указан как -, то читается стандартный ввод. При чтении из стандартного ввода разархивируются только файлы, поддерживаемые xz(1). Другие файлы предполагаются уже в не сжатом виде. Большинство опций grep(1) поддерживается. Однако, следующие опции не поддерживаются: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep является псевдонимом для xzgrep -E. xzfgrep является псевдонимом для xzgrep -F. Команды lzgrep, lzegrep и lzfgrep предоставлены для обратной совместимости с LZMA Utils. EXIT STATUS 0 Хотя бы одно совпадение было найдено в хотя бы одном из входных файлов. Ошибок не возникло. 1 Совпадений не было найдено ни в одном из входных файлов. Ошибок не возникло. >1 Произошла одна или несколько ошибок. Неизвестно, были ли найдены совпадения. ENVIRONMENT GREP Если GREP установлен в ненулевое значение, то оно используется вместо grep, grep -E или grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - search possibly-compressed files for patterns SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep invokes grep(1) on uncompressed contents of files. The formats of the files are determined from the filename suffixes. Any file with a suffix supported by xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) will be decompressed; all other files are assumed to be uncom‐ pressed. If no files are specified or file is - then standard input is read. When reading from standard input, only files supported by xz(1) are de‐ compressed. Other files are assumed to be in uncompressed form al‐ ready. Most options of grep(1) are supported. However, the following options are not supported: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep is an alias for xzgrep -E. xzfgrep is an alias for xzgrep -F. The commands lzgrep, lzegrep, and lzfgrep are provided for backward compatibility with LZMA Utils. EXIT STATUS 0 At least one match was found from at least one of the input files. No errors occurred. 1 No matches were found from any of the input files. No errors occurred. >1 One or more errors occurred. It is unknown if matches were found. ENVIRONMENT GREP If GREP is set to a non-empty value, it is used instead of grep, grep -E, or grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - сравнение сжатых файлов SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp и xzdiff сравнивают несжатое содержимое двух файлов. Несжатые данные и опции передаются в cmp(1) или diff(1), если не указаны --help или --version. Если указаны как file1, так и file2, они могут быть несжатыми файлами или файлами в форматах, которые могут распаковывать xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1). Необходимые команды распаковки определяются по суффиксам имён файлов file1 и file2. Файл с неизвестным суффиксом предполагается несжатым или в формате, который может распаковывать xz(1). Если предоставлено только одно имя файла, file1 должен иметь суффикс поддерживаемого формата сжатия, и имя file2 предполагается равным file1 без суффикса формата сжатия. Команды lzcmp и lzdiff предоставлены для обеспечения обратной совместимости с LZMA Utils. EXIT STATUS Если возникает ошибка распаковки, код завершения равен 2. В противном случае используется код завершения cmp(1) или diff(1). SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - compare compressed files SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp and xzdiff compare uncompressed contents of two files. Uncom‐ pressed data and options are passed to cmp(1) or diff(1) unless --help or --version is specified. If both file1 and file2 are specified, they can be uncompressed files or files in formats that xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) can decompress. The required decompression commands are deter‐ mined from the filename suffixes of file1 and file2. A file with an unknown suffix is assumed to be either uncompressed or in a format that xz(1) can decompress. If only one filename is provided, file1 must have a suffix of a sup‐ ported compression format and the name for file2 is assumed to be file1 with the compression format suffix removed. The commands lzcmp and lzdiff are provided for backward compatibility with LZMA Utils. EXIT STATUS If a decompression error occurs, the exit status is 2. Otherwise the exit status of cmp(1) or diff(1) is used. SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - сравнение сжатых файлов SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp и xzdiff сравнивают несжатое содержимое двух файлов. Несжатые данные и опции передаются в cmp(1) или diff(1), если не указаны --help или --version. Если указаны оба file1 и file2, они могут быть несжатыми файлами или файлами в форматах, которые могут разжать xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1). Необходимые команды разжатия определяются по суффиксам имён файлов file1 и file2. Файл с неизвестным суффиксом считается либо несжатым, либо в формате, который может разжать xz(1). Если предоставлено только одно имя файла, file1 должен иметь суффикс поддерживаемого формата сжатия, и имя file2 предполагается как file1 без суффикса формата сжатия. Команды lzcmp и lzdiff предоставлены для обеспечения обратной совместимости с LZMA Utils. EXIT STATUS Если возникает ошибка разжатия, код выхода равен 2. В противном случае используется код выхода cmp(1) или diff(1). SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZDIFF(1) XZ Utils XZDIFF(1) NAME xzcmp, xzdiff, lzcmp, lzdiff - compare compressed files SYNOPSIS xzcmp [option...] file1 [file2] xzdiff ... lzcmp ... lzdiff ... DESCRIPTION xzcmp and xzdiff compare uncompressed contents of two files. Uncom‐ pressed data and options are passed to cmp(1) or diff(1) unless --help or --version is specified. If both file1 and file2 are specified, they can be uncompressed files or files in formats that xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) can decompress. The required decompression commands are deter‐ mined from the filename suffixes of file1 and file2. A file with an unknown suffix is assumed to be either uncompressed or in a format that xz(1) can decompress. If only one filename is provided, file1 must have a suffix of a sup‐ ported compression format and the name for file2 is assumed to be file1 with the compression format suffix removed. The commands lzcmp and lzdiff are provided for backward compatibility with LZMA Utils. EXIT STATUS If a decompression error occurs, the exit status is 2. Otherwise the exit status of cmp(1) or diff(1) is used. SEE ALSO cmp(1), diff(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1) Tukaani 2024-02-13 XZDIFF(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - поиск шаблонов в возможно сжатых файлах SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep вызывает grep(1) для не сжатого содержимого файлов. Форматы файлов определяются по суффиксам имён файлов. Любые файлы с суффиксами, поддерживаемыми xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1), будут разархивированы; все остальные файлы предполагаются не сжатыми. Если файлы не указаны или файл имеет значение -, то читается стандартный ввод. При чтении из стандартного ввода, только файлы, поддерживаемые xz(1), разархивируются. Другие файлы предполагаются уже в не сжатой форме. Большинство опций grep(1) поддерживаются. Однако, следующие опции не поддерживаются: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep является псевдонимом для xzgrep -E. xzfgrep является псевдонимом для xzgrep -F. Команды lzgrep, lzegrep и lzfgrep предоставляются для обратной совместимости с LZMA Utils. EXIT STATUS 0 По крайней мере, одно совпадение было найдено в по крайней мере одном из входных файлов. Не возникло ошибок. 1 Не найдено совпадений в ни одном из входных файлов. Не возникло ошибок. >1 Возникла одна или несколько ошибок. Неизвестно, были ли найдены совпадения. ENVIRONMENT GREP Если GREP установлен в непустое значение, оно используется вместо grep, grep -E или grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - search possibly-compressed files for patterns SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep invokes grep(1) on uncompressed contents of files. The formats of the files are determined from the filename suffixes. Any file with a suffix supported by xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) will be decompressed; all other files are assumed to be uncom‐ pressed. If no files are specified or file is - then standard input is read. When reading from standard input, only files supported by xz(1) are de‐ compressed. Other files are assumed to be in uncompressed form al‐ ready. Most options of grep(1) are supported. However, the following options are not supported: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep is an alias for xzgrep -E. xzfgrep is an alias for xzgrep -F. The commands lzgrep, lzegrep, and lzfgrep are provided for backward compatibility with LZMA Utils. EXIT STATUS 0 At least one match was found from at least one of the input files. No errors occurred. 1 No matches were found from any of the input files. No errors occurred. >1 One or more errors occurred. It is unknown if matches were found. ENVIRONMENT GREP If GREP is set to a non-empty value, it is used instead of grep, grep -E, or grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - поиск шаблонов в возможно сжатых файлах SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep вызывает grep(1) для не сжатого содержимого файлов. Форматы файлов определяются по суффиксам имён файлов. Любой файл с суффиксом, поддерживаемым xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1), будет разархивирован; все остальные файлы предполагаются не сжатыми. Если файлы не указаны или файл -, то читается стандартный ввод. При чтении из стандартного ввода, только файлы, поддерживаемые xz(1), разархивируются. Другие файлы предполагаются уже в не сжатом виде. Большинство опций grep(1) поддерживаются. Однако, следующие опции не поддерживаются: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep является псевдонимом для xzgrep -E. xzfgrep является псевдонимом для xzgrep -F. Команды lzgrep, lzegrep и lzfgrep предоставлены для обратной совместимости с LZMA Utils. EXIT STATUS 0 По крайней мере, одно совпадение было найдено в по крайней мере одном из входных файлов. Не возникло ошибок. 1 Не найдено совпадений в ни одном из входных файлов. Не возникло ошибок. >1 Произошла одна или более ошибок. Неизвестно, были ли найдены совпадения. ENVIRONMENT GREP Если GREP установлен в непустое значение, оно используется вместо grep, grep -E или grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - search possibly-compressed files for patterns SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep invokes grep(1) on uncompressed contents of files. The formats of the files are determined from the filename suffixes. Any file with a suffix supported by xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) will be decompressed; all other files are assumed to be uncom‐ pressed. If no files are specified or file is - then standard input is read. When reading from standard input, only files supported by xz(1) are de‐ compressed. Other files are assumed to be in uncompressed form al‐ ready. Most options of grep(1) are supported. However, the following options are not supported: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep is an alias for xzgrep -E. xzfgrep is an alias for xzgrep -F. The commands lzgrep, lzegrep, and lzfgrep are provided for backward compatibility with LZMA Utils. EXIT STATUS 0 At least one match was found from at least one of the input files. No errors occurred. 1 No matches were found from any of the input files. No errors occurred. >1 One or more errors occurred. It is unknown if matches were found. ENVIRONMENT GREP If GREP is set to a non-empty value, it is used instead of grep, grep -E, or grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - поиск шаблонов в возможно сжатых файлах SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep вызывает grep(1) на разархивированном содержимом файлов. Форматы файлов определяются из суффиксов имён файлов. Любые файлы с суффиксами, поддерживаемыми xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1), будут разархивированы; все другие файлы предполагаются не сжатыми. Если файлы не указаны или файл - , то читается стандартный ввод. При чтении из стандартного ввода, только файлы, поддерживаемые xz(1), разархивируются. Другие файлы предполагаются уже в не сжатом виде. Большинство опций grep(1) поддерживаются. Однако, следующие опции не поддерживаются: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep является псевдонимом для xzgrep -E. xzfgrep является псевдонимом для xzgrep -F. Команды lzgrep, lzegrep и lzfgrep предоставлены для обратной совместимости с LZMA Utils. EXIT STATUS 0 По крайней мере, одно совпадение было найдено в по крайней мере одном из входных файлов. Не возникло ошибок. 1 Не было найдено совпадений в ни одном из входных файлов. Не возникло ошибок. >1 Произошла одна или более ошибок. Неизвестно, были ли найдены совпадения. ENVIRONMENT GREP Если GREP установлен в непустое значение, оно используется вместо grep, grep -E или grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - search possibly-compressed files for patterns SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep invokes grep(1) on uncompressed contents of files. The formats of the files are determined from the filename suffixes. Any file with a suffix supported by xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) will be decompressed; all other files are assumed to be uncom‐ pressed. If no files are specified or file is - then standard input is read. When reading from standard input, only files supported by xz(1) are de‐ compressed. Other files are assumed to be in uncompressed form al‐ ready. Most options of grep(1) are supported. However, the following options are not supported: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep is an alias for xzgrep -E. xzfgrep is an alias for xzgrep -F. The commands lzgrep, lzegrep, and lzfgrep are provided for backward compatibility with LZMA Utils. EXIT STATUS 0 At least one match was found from at least one of the input files. No errors occurred. 1 No matches were found from any of the input files. No errors occurred. >1 One or more errors occurred. It is unknown if matches were found. ENVIRONMENT GREP If GREP is set to a non-empty value, it is used instead of grep, grep -E, or grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - поиск шаблонов в возможно сжатых файлах SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep вызывает grep(1) на не сжатом содержимом файлов. Форматы файлов определяются по суффиксам имён файлов. Любые файлы с суффиксами, поддерживаемыми xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1), будут распакованы; все другие файлы предполагаются не сжатыми. Если файлы не указаны или файл указан как -, то читается стандартный ввод. При чтении из стандартного ввода, только файлы, поддерживаемые xz(1), распаковываются. Другие файлы предполагаются уже в не сжатом виде. Большинство опций grep(1) поддерживаются. Однако, следующие опции не поддерживаются: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep является псевдонимом для xzgrep -E. xzfgrep является псевдонимом для xzgrep -F. Команды lzgrep, lzegrep и lzfgrep предоставляются для обратной совместимости с LZMA Utils. EXIT STATUS 0 По крайней мере, одно совпадение было найдено в по крайней мере одном из входных файлов. Не произошло ошибок. 1 Совпадения не были найдены ни в одном из входных файлов. Не произошло ошибок. >1 Произошла одна или более ошибок. Неизвестно, были ли найдены совпадения. ENVIRONMENT GREP Если GREP установлен в непустое значение, он используется вместо grep, grep -E или grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - search possibly-compressed files for patterns SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep invokes grep(1) on uncompressed contents of files. The formats of the files are determined from the filename suffixes. Any file with a suffix supported by xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) will be decompressed; all other files are assumed to be uncom‐ pressed. If no files are specified or file is - then standard input is read. When reading from standard input, only files supported by xz(1) are de‐ compressed. Other files are assumed to be in uncompressed form al‐ ready. Most options of grep(1) are supported. However, the following options are not supported: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep is an alias for xzgrep -E. xzfgrep is an alias for xzgrep -F. The commands lzgrep, lzegrep, and lzfgrep are provided for backward compatibility with LZMA Utils. EXIT STATUS 0 At least one match was found from at least one of the input files. No errors occurred. 1 No matches were found from any of the input files. No errors occurred. >1 One or more errors occurred. It is unknown if matches were found. ENVIRONMENT GREP If GREP is set to a non-empty value, it is used instead of grep, grep -E, or grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) Утилиты XZ XZGREP(1) NAME xzgrep - поиск шаблонов в возможно сжатых файлах SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep вызывает grep(1) на разархивированном содержимом файлов. Форматы файлов определяются по их расширениям. Любые файлы с расширениями, поддерживаемыми xz(1), gzip(1), bzip2(1), lzop(1), zstd(1) или lz4(1), будут разархивированы; все остальные файлы предполагаются не сжатыми. Если файлы не указаны или указан файл -, то читается стандартный ввод. При чтении из стандартного ввода разархивируются только файлы, поддерживаемые xz(1). Другие файлы предполагаются уже в не сжатой форме. Большинство опций grep(1) поддерживается. Однако, следующие опции не поддерживаются: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep является псевдонимом для xzgrep -E. xzfgrep является псевдонимом для xzgrep -F. Команды lzgrep, lzegrep и lzfgrep предоставлены для обратной совместимости с LZMA Utils. EXIT STATUS 0 По крайней мере, одно совпадение было найдено в по крайней мере одном из входных файлов. Ошибок не возникло. 1 Совпадения не были найдены ни в одном из входных файлов. Ошибок не возникло. >1 Произошла одна или несколько ошибок. Неизвестно, были ли найдены совпадения. ENVIRONMENT GREP Если GREP установлен в значение, отличное от пустого, то оно используется вместо grep, grep -E или grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZGREP(1) XZ Utils XZGREP(1) NAME xzgrep - search possibly-compressed files for patterns SYNOPSIS xzgrep [option...] [pattern_list] [file...] xzegrep ... xzfgrep ... lzgrep ... lzegrep ... lzfgrep ... DESCRIPTION xzgrep invokes grep(1) on uncompressed contents of files. The formats of the files are determined from the filename suffixes. Any file with a suffix supported by xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), or lz4(1) will be decompressed; all other files are assumed to be uncom‐ pressed. If no files are specified or file is - then standard input is read. When reading from standard input, only files supported by xz(1) are de‐ compressed. Other files are assumed to be in uncompressed form al‐ ready. Most options of grep(1) are supported. However, the following options are not supported: -r, --recursive -R, --dereference-recursive -d, --directories=action -Z, --null -z, --null-data --include=glob --exclude=glob --exclude-from=file --exclude-dir=glob xzegrep is an alias for xzgrep -E. xzfgrep is an alias for xzgrep -F. The commands lzgrep, lzegrep, and lzfgrep are provided for backward compatibility with LZMA Utils. EXIT STATUS 0 At least one match was found from at least one of the input files. No errors occurred. 1 No matches were found from any of the input files. No errors occurred. >1 One or more errors occurred. It is unknown if matches were found. ENVIRONMENT GREP If GREP is set to a non-empty value, it is used instead of grep, grep -E, or grep -F. SEE ALSO grep(1), xz(1), gzip(1), bzip2(1), lzop(1), zstd(1), lz4(1), zgrep(1) Tukaani 2024-02-13 XZGREP(1)
XZLESS(1) XZ Utils XZLESS(1) NAME xzless, lzless - просмотр сжатых файлов xz или lzma (текстовых) SYNOPSIS xzless [file...] lzless [file...] DESCRIPTION xzless — это фильтр, который отображает текст из сжатых файлов на терминале. Файлы, поддерживаемые xz(1), распаковываются; другие файлы предполагаются уже несжатыми. Если файлы не указаны, xzless читает из стандартного ввода. xzless использует less(1) для вывода. В отличие от xzmore, выбор пейджера нельзя изменить с помощью переменной окружения. Команды основаны на more(1) и vi(1) и позволяют перемещаться вперёд и назад, а также выполнять поиск. Для получения дополнительной информации см. руководство less(1). Команда lzless предоставлена для обратной совместимости с LZMA Utils. ENVIRONMENT LESSMETACHARS Список символов, специальных для оболочки. Устанавливается xzless, если ещё не задан в окружении. LESSOPEN Устанавливается в командную строку для вызова декомпрессора xz(1) для предварительной обработки входных файлов для less(1). SEE ALSO less(1), xz(1), xzmore(1), zless(1) Tukaani 2024-02-12 XZLESS(1)
XZLESS(1) XZ Utils XZLESS(1) NAME xzless, lzless - view xz or lzma compressed (text) files SYNOPSIS xzless [file...] lzless [file...] DESCRIPTION xzless is a filter that displays text from compressed files to a termi‐ nal. Files supported by xz(1) are decompressed; other files are as‐ sumed to be in uncompressed form already. If no files are given, xz‐ less reads from standard input. xzless uses less(1) to present its output. Unlike xzmore, its choice of pager cannot be altered by setting an environment variable. Com‐ mands are based on both more(1) and vi(1) and allow back and forth movement and searching. See the less(1) manual for more information. The command named lzless is provided for backward compatibility with LZMA Utils. ENVIRONMENT LESSMETACHARS A list of characters special to the shell. Set by xzless unless it is already set in the environment. LESSOPEN Set to a command line to invoke the xz(1) decompressor for pre‐ processing the input files to less(1). SEE ALSO less(1), xz(1), xzmore(1), zless(1) Tukaani 2024-02-12 XZLESS(1)
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Сжатие или распаковка файлов .xz и .lzma SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz эквивалентно xz --decompress. xzcat эквивалентно xz --decompress --stdout. lzma эквивалентно xz --format=lzma. unlzma эквивалентно xz --format=lzma --decompress. lzcat эквивалентно xz --format=lzma --decompress --stdout. При написании скриптов, которым требуется распаковка файлов, рекомендуется всегда использовать имя xz с соответствующими аргументами (xz -d или xz -dc) вместо имен unxz и xzcat. DESCRIPTION xz - это универсальный инструмент сжатия данных с синтаксисом командной строки, подобным gzip(1) и bzip2(1). Исходный формат файлов - .xz, но поддерживаются также устаревший формат .lzma, используемый в LZMA Utils, и необработанные сжатые потоки без заголовков контейнера. Кроме того, поддерживается распаковка формата .lz, используемого lzip. xz сжимает или распаковывает каждый файл в соответствии с выбранным режимом операции. Если файлы не указаны или указан файл -, xz читает из стандартного ввода и записывает обработанные данные в стандартный вывод. xz отказывается (выводит ошибку и пропускает файл) записывать сжатые данные в стандартный вывод, если он является терминалом. Аналогично, xz отказывается читать сжатые данные из стандартного ввода, если он является терминалом. Если не указан --stdout, файлы, отличные от -, записываются в новый файл, имя которого получается из имени исходного файла: • При сжатии, суффикс целевого формата файла (.xz или .lzma) добавляется к имени исходного файла для получения имени целевого файла. • При распаковке, суффикс .xz, .lzma или .lz удаляется из имени файла для получения имени целевого файла. xz также распознает суффиксы .txz и .tlz и заменяет их на суффикс .tar. Если целевой файл уже существует, выводится ошибка и файл пропускается. Если не происходит запись в стандартный вывод, xz выводит предупреждение и пропускает файл, если выполняется одно из следующих условий: • Файл не является обычным файлом. Символические ссылки не отслеживаются и поэтому не считаются обычными файлами. • Файл имеет более одной жесткой ссылки. • Файл имеет установленными биты setuid, setgid или sticky. • Режим операции установлен на сжатие и файл уже имеет суффикс целевого формата файла (.xz или .txz при сжатии в формат .xz, и .lzma или .tlz при сжатии в формат .lzma). • Режим операции установлен на распаковку и файл не имеет суффикса ни одного из поддерживаемых форматов файлов (.xz, .txz, .lzma, .tlz или .lz). После успешного сжатия или распаковки файла xz копирует владельца, группу, права доступа, время доступа и время модификации из исходного файла в целевой файл. Если копирование группы не удается, права доступа модифицируются так, чтобы целевой файл не стал доступным для пользователей, у которых не было доступа к исходному файлу. xz пока не поддерживает копирование других метаданных, таких как списки контроля доступа или расширенные атрибуты. Как только целевой файл успешно закрыт, исходный файл удаляется, если не указан --keep. Исходный файл никогда не удаляется, если вывод записывается в стандартный вывод или если возникает ошибка. Отправка сигнала SIGINFO или SIGUSR1 процессу xz заставляет его выводить информацию о прогрессе в стандартный вывод ошибок. Это имеет ограниченное применение, поскольку если стандартный вывод ошибок является терминалом, использование --verbose отобразит автоматически обновляющийся индикатор прогресса. Memory usage Использование памяти xz варьируется от нескольких сотен килобайт до нескольких гигабайт в зависимости от настроек сжатия. Настройки, используемые при сжатии файла, определяют требования к памяти декомпрессора. Обычно декомпрессору требуется 5%–20% от количества памяти, которое потребовалось компрессору при создании файла. Например, распаковка файла, созданного с помощью xz -9, в настоящее время требует 65 MiB памяти. Тем не менее, возможно наличие файлов .xz, которые требуют нескольких гигабайт памяти для распаковки. Особенно пользователи старых систем могут найти возможность очень большого использования памяти раздражающей. Чтобы предотвратить неприятные сюрпризы, xz имеет встроенный лимитер использования памяти, который по умолчанию отключен. Хотя некоторые операционные системы предоставляют способы ограничения использования памяти процессами, полагаться на это не считалось достаточно гибким (например, использование ulimit(1) для ограничения виртуальной памяти имеет тенденцию нарушать mmap(2)). Лимитер использования памяти можно включить с помощью опции командной строки --memlimit=limit. Часто удобнее включить лимитер по умолчанию, установив переменную окружения XZ_DEFAULTS, например, XZ_DEFAULTS=--memlimit=150MiB. Возможна установка лимитов отдельно для сжатия и распаковки с помощью --memlimit-compress=limit и --memlimit-decompress=limit. Использование этих двух опций вне XZ_DEFAULTS редко бывает полезным, поскольку один запуск xz не может выполнять как сжатие, так и распаковку, и --memlimit=limit (или -M limit) короче для ввода в командной строке. Если указанный лимит использования памяти превышен при распаковке, xz выведет ошибку и распаковка файла не удастся. Если лимит превышен при сжатии, xz попытается уменьшить настройки так, чтобы лимит больше не превышался (кроме случаев использования --format=raw или --no-adjust). Таким образом, операция не завершится неудачей, если лимит не слишком мал. Масштабирование настроек выполняется в шагах, которые не соответствуют пресетам уровней сжатия, например, если лимит немного меньше количества, требуемого для xz -9, настройки будут уменьшены только немного, а не до xz -8. Concatenation and padding with .xz files Возможна конкатенация файлов .xz как есть. xz будет распаковывать такие файлы, как будто это один файл .xz. Возможна вставка заполнителя между конкатенированными частями или после последней части. Заполнитель должен состоять из нулевых байтов, а его размер должен быть кратным четырем байтам. Это может быть полезно, например, если файл .xz хранится на носителе, который измеряет размеры файлов в блоках по 512 байт. Конкатенация и заполнение не допускаются для файлов .lzma или необработанных потоков. OPTIONS Integer suffixes and special values В большинстве мест, где ожидается целочисленный аргумент, поддерживается необязательный суффикс для удобного указания больших целых чисел. Между целым числом и суффиксом не должно быть пробелов. KiB Умножает целое число на 1 024 (2^10). Ki, k, kB, K и KB принимаются как синонимы KiB. MiB Умножает целое число на 1 048 576 (2^20). Mi, m, M и MB принимаются как синонимы MiB. GiB Умножает целое число на 1 073 741 824 (2^30). Gi, g, G и GB принимаются как синонимы GiB. Специальное значение max может использоваться для указания максимального целочисленного значения, поддерживаемого опцией. Operation mode Если указано несколько опций режима операции, последняя вступает в силу. -z, --compress Сжатие. Это режим операции по умолчанию, когда ни одна опция режима операции не указана и другой режим не подразумевается из имени команды (например, unxz подразумевает --decompress). После успешного сжатия исходный файл удаляется, если не происходит запись в стандартный вывод или не указан --keep. -d, --decompress, --uncompress Распаковка. После успешной распаковки исходный файл удаляется, если не происходит запись в стандартный вывод или не указан --keep. -t, --test Проверка целостности сжатых файлов. Эта опция эквивалентна --decompress --stdout, за исключением того, что распакованные данные отбрасываются вместо записи в стандартный вывод. Файлы не создаются и не удаляются. -l, --list Вывод информации о сжатых файлах. Не производится распакованного вывода, и файлы не создаются или не удаляются. В режиме списка программа не может читать сжатые данные из стандартного ввода или из других неподвижных источников. По умолчанию список показывает базовую информацию о файлах, один файл на строку. Для получения более подробной информации используйте также опцию --verbose. Для еще большего количества информации используйте --verbose дважды, но помните, что это может быть медленно, поскольку получение всей дополнительной информации требует многих поисков. Ширина подробного вывода превышает 80 символов, поэтому перенаправление вывода в, например, less -S может быть удобным, если терминал недостаточно широкий. Точный вывод может варьироваться между версиями xz и разными локалями. Для машинно-читаемого вывода используйте --robot --list. Operation modifiers -k, --keep Не удалять исходные файлы. С версии xz 5.2.6 эта опция также заставляет xz сжимать или распаковывать, даже если вход - это символическая ссылка на обычный файл, имеет более одной жесткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. В более ранних версиях это делалось только с --force. -f, --force Эта опция имеет несколько эффектов: • Если целевой файл уже существует, удалить его перед сжатием или распаковкой. • Сжимать или распаковывать, даже если вход - это символическая ссылка на обычный файл, имеет более одной жесткой ссылки или имеет установленные биты setuid, setgid или sticky. Биты setuid, setgid и sticky не копируются в целевой файл. • При использовании с --decompress --stdout, если xz не может распознать тип исходного файла, скопировать исходный файл как есть в стандартный вывод. Это позволяет использовать xzcat --force как cat(1) для файлов, которые не были сжаты с xz. Обратите внимание, что в будущем xz может поддерживать новые сжатые форматы файлов, что может заставить xz распаковывать больше типов файлов вместо копирования их как есть в стандартный вывод. --format=format можно использовать для ограничения xz распаковкой только одного формата файла. -c, --stdout, --to-stdout Записывать сжатые или распакованные данные в стандартный вывод вместо файла. Это подразумевает --keep. --single-stream Распаковывать только первый поток .xz и молча игнорировать возможные оставшиеся входные данные после потока. Нормально такие завершающие мусорные данные заставляют xz выводить ошибку. xz никогда не распаковывает более одного потока из файлов .lzma или необработанных потоков, но эта опция все равно заставляет xz игнорировать возможные завершающие данные после файла .lzma или необработанного потока. Эта опция не имеет эффекта, если режим операции не --decompress или --test. --no-sparse Отключить создание разреженных файлов. По умолчанию, если распаковка происходит в обычный файл, xz пытается сделать файл разреженным, если распакованные данные содержат длинные последовательности двоичных нулей. Это также работает при записи в стандартный вывод, если стандартный вывод подключен к обычному файлу и выполняются определенные дополнительные условия для безопасности. Создание разреженных файлов может сэкономить место на диске и ускорить распаковку, уменьшив количество операций ввода/вывода. -S .suf, --suffix=.suf При сжатии, использовать .suf в качестве суффикса для целевого файла вместо .xz или .lzma. Если не происходит запись в стандартный вывод и исходный файл уже имеет суффикс .suf, выводится предупреждение и файл пропускается. При распаковке, распознавать файлы с суффиксом .suf в дополнение к файлам с суффиксами .xz, .txz, .lzma, .tlz или .lz. Если исходный файл имеет суффикс .suf, суффикс удаляется для получения имени целевого файла. При сжатии или распаковке необработанных потоков (--format=raw), суффикс всегда должен быть указан, если не происходит запись в стандартный вывод, поскольку для необработанных потоков нет суффикса по умолчанию. --files[=file] Читать имена файлов для обработки из file; если file omitted, имена файлов читаются из стандартного ввода. Имена файлов должны быть завершены символом новой строки. Точка (-) считается обычным именем файла; она не означает стандартный ввод. Если имена файлов также указаны как аргументы командной строки, они обрабатываются перед именами файлов, прочитанными из file. --files0[=file] Это идентично --files[=file], за исключением того, что каждое имя файла должно быть завершено нулевым символом. Basic file format and compression options -F format, --format=format Указать формат файла для сжатия или распаковки: auto Это значение по умолчанию. При сжатии auto эквивалентно xz. При распаковке формат входного файла определяется автоматически. Обратите внимание, что необработанные потоки (созданные с --format=raw) не могут быть обнаружены автоматически. xz Сжимать в формат .xz или принимать только файлы .xz при распаковке. lzma, alone Сжимать в устаревший формат .lzma или принимать только файлы .lzma при распаковке. Альтернативное имя alone предоставлено для обратной совместимости с LZMA Utils. lzip Принимать только файлы .lz при распаковке. Сжатие не поддерживается. Поддерживаются версии формата .lz 0 и нерасширенная версия 1. Файлы версии 0 создавались lzip 1.3 и старше. Такие файлы не распространены, но могут быть найдены в архивах файлов, поскольку несколько исходных пакетов были выпущены в этом формате. Люди могут иметь старые личные файлы в этом формате. Поддержка распаковки формата версии 0 была удалена в lzip 1.18. lzip 1.4 и новее создают файлы в формате версии 1. Расширение маркера синхронизированной очистки для формата версии 1 было добавлено в lzip 1.6. Это расширение редко используется и не поддерживается xz (диагностируется как поврежденный вход). raw Сжимать или распаковывать необработанный поток (без заголовков). Это предназначено только для продвинутых пользователей. Для декодирования необработанных потоков вам нужно использовать --format=raw и явно указать цепочку фильтров, которая обычно хранилась бы в заголовках контейнера. -C check, --check=check Указать тип проверки целостности. Проверка рассчитывается из несжатых данных и хранится в файле .xz. Эта опция имеет эффект только при сжатии в формат .xz; формат .lzma не поддерживает проверки целостности. Проверка целостности (если есть) проверяется при распаковке файла .xz. Поддерживаемые типы проверок: none Не рассчитывать проверку целостности. Это обычно плохая идея. Это может быть полезно, когда целостность данных проверяется другими средствами. crc32 Рассчитывать CRC32 с использованием полинома из IEEE-802.3 (Ethernet). crc64 Рассчитывать CRC64 с использованием полинома из ECMA-182. Это значение по умолчанию, поскольку оно немного лучше, чем CRC32, для обнаружения поврежденных файлов, а разница в скорости незначительна. sha256 Рассчитывать SHA-256. Это немного медленнее, чем CRC32 и CRC64. Целостность заголовков .xz всегда проверяется с CRC32. Это не возможно изменить или отключить. --ignore-check Не проверять проверку целостности сжатых данных при распаковке. Значения CRC32 в заголовках .xz все равно будут проверены нормально. Не используйте эту опцию, если вы не знаете, что делаете. Возможные причины использования этой опции: • Попытка восстановить данные из поврежденного файла .xz. • Увеличение скорости распаковки. Это имеет значение в основном с SHA-256 или с файлами, которые сжаты очень хорошо. Рекомендуется не использовать эту опцию для этой цели, если целостность файла проверяется внешне другим способом. -0 ... -9 Выбрать пресет уровня сжатия. По умолчанию -6. Если указано несколько пресетов, последний вступает в силу. Если уже была указана пользовательская цепочка фильтров, установка пресета уровня сжатия сбрасывает пользовательскую цепочку фильтров. Различия между пресетами более значительны, чем с gzip(1) и bzip2(1). Выбранные настройки сжатия определяют требования к памяти декомпрессора, поэтому использование слишком высокого пресета уровня может сделать распаковку болезненной на старых системах с малым объемом ОЗУ. В частности, не стоит слепо использовать -9 для всего, как это часто бывает с gzip(1) и bzip2(1). -0 ... -3 Это относительно быстрые пресеты. -0 иногда быстрее, чем gzip -9, при значительно лучшем сжатии. Более высокие пресеты часто имеют скорость, сравнимую с bzip2(1), с сопоставимым или лучшим коэффициентом сжатия, хотя результаты сильно зависят от типа сжимаемых данных. -4 ... -6 Хорошее до очень хорошего сжатия при разумном использовании памяти декомпрессором даже для старых систем. -6 - это значение по умолчанию, которое обычно является хорошим выбором для распространения файлов, которые должны распаковываться даже на системах с только 16 MiB ОЗУ. (-5e или -6e также стоит рассмотреть. См. --extreme.) -7 ... -9 Это как -6, но с более высокими требованиями к памяти компрессора и декомпрессора. Это полезно только при сжатии файлов больше 8 MiB, 16 MiB и 32 MiB соответственно. На том же оборудовании скорость распаковки приблизительно постоянна в количестве байт сжатых данных в секунду. Другими словами, чем лучше сжатие, тем быстрее обычно будет распаковка. Это также означает, что количество несжатого вывода, производимого в секунду, может сильно варьироваться. В следующей таблице суммируются особенности пресетов: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Описание столбцов: • DictSize - размер словаря LZMA2. Трата памяти на использование словаря больше, чем размер несжатого файла. Поэтому лучше избегать использования пресетов -7 ... -9, если в них нет реальной необходимости. На -6 и ниже, количество потраченной впустую памяти обычно достаточно мало, чтобы не иметь значения. • CompCPU - упрощенное представление настроек LZMA2, которые влияют на скорость сжатия. Размер словаря также влияет на скорость, так что, несмотря на то, что CompCPU одинаков для уровней -6 ... -9, более высокие уровни все равно склонны быть немного медленнее. Для получения еще более медленного и, возможно, лучшего сжатия см. --extreme. • CompMem - требования к памяти компрессора в однопоточном режиме. Это может немного варьироваться между версиями xz. • DecMem - требования к памяти декомпрессора. То есть, настройки сжатия определяют требования к памяти декомпрессора. Точное использование памяти декомпрессором немного больше, чем размер словаря LZMA2, но значения в таблице округлены вверх до следующего полного MiB. Требования к памяти в многопоточном режиме значительно выше, чем в однопоточном режиме. С значением --block-size по умолчанию каждый поток требует 3*3*DictSize плюс CompMem или DecMem. Например, четыре потока с пресетом -6 требуют 660–670 MiB памяти. -e, --extreme Использовать более медленную версию выбранного пресета уровня сжатия (-0 ... -9), чтобы, hopefully, получить немного лучшее соотношение сжатия, но с неудачей это может сделать его хуже. Использование памяти декомпрессором не затрагивается, но использование памяти компрессором немного увеличивается на пресетах -0 ... -3. Поскольку есть два пресета с размерами словарей 4 MiB и 8 MiB, пресеты -3e и -5e используют немного более быстрые настройки (нижний CompCPU), чем -4e и -6e соответственно. Таким образом, ни два пресета не идентичны. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB Например, всего четыре пресета используют словарь 8 MiB, порядок от самого быстрого к самому медленному - -5, -6, -5e и -6e. --fast --best Эти - это несколько вводящие в заблуждение псевдонимы для -0 и -9 соответственно. Они предоставлены только для обратной совместимости с LZMA Utils. Избегайте использования этих опций. --block-size=size При сжатии в формат .xz, разделить входные данные на блоки по size байт. Блоки сжимаются независимо друг от друга, что помогает с многопоточностью и делает возможной ограниченную произвольную доступную распаковку. Эта опция обычно используется для переопределения размера блока по умолчанию в многопоточном режиме, но ее можно использовать и в однопоточном режиме. В многопоточном режиме примерно трижды size байт будут выделены в каждом потоке для буферизации входа и выхода. Значение по умолчанию - три размера словаря LZMA2 или 1 MiB, в зависимости от того, что больше. Обычно хорошее значение - 2–4 раза больше размера словаря LZMA2 или как минимум 1 MiB. Использование size меньше размера словаря LZMA2 - трата ОЗУ, поскольку буфер словаря LZMA2 никогда не будет полностью использован. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Эта информация о размере необходима для многопоточной распаковки. В однопоточном режиме разделение на блоки по умолчанию не выполняется. Установка этой опции не влияет на использование памяти. Информация о размере не хранится в заголовках блоков, поэтому файлы, созданные в однопоточном режиме, не будут идентичны файлам, созданным в многопоточном режиме. Отсутствие информации о размере также означает, что xz не сможет распаковывать файлы в многопоточном режиме. --block-list=items При сжатии в формат .xz, начать новый блок с необязательной пользовательской цепочкой фильтров после указанных интервалов несжатых данных. items - список, разделенный запятыми. Каждый элемент состоит из необязательного номера цепочки фильтров от 0 до 9, за которым следует двоеточие (:) и обязательный размер несжатых данных. Пропуск элемента (две или более последовательные запятые) подразумевает использование размера и фильтров предыдущего элемента. Если входной файл больше суммы размеров в items, последний элемент повторяется до конца файла. Специальное значение 0 может использоваться как последний размер, чтобы указать, что остаток файла должен быть закодирован как один блок. Альтернативную цепочку фильтров для каждого блока можно указать в сочетании с опциями --filters1=filters ... --filters9=filters. Эти опции определяют цепочки фильтров с идентификатором от 1 до 9. Цепочка фильтров 0 может использоваться для ссылки на цепочку фильтров по умолчанию, которая является той же, что и без указания цепочки фильтров. Идентификатор цепочки фильтров можно использовать перед размером несжатых данных, за которым следует двоеточие (:). Например, если указать --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB, то блоки будут созданы с использованием: • Цепочки фильтров, указанной в --filters1 и 2 MiB входа. • Цепочки фильтров, указанной в --filters3 и 2 MiB входа. • Цепочки фильтров, указанной в --filters2 и 4 MiB входа. • Цепочки фильтров, указанной в --filters2 и 4 MiB входа. • Цепочки фильтров по умолчанию и 2 MiB входа. • Цепочки фильтров по умолчанию и 4 MiB входа для каждого блока до конца входа. Если указать размер, превышающий размер блока энкодера (либо значение по умолчанию в потоковом режиме, либо значение, указанное с --block-size=size), энкодер создаст дополнительные блоки, сохраняя границы, указанные в items. Например, если указать --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB и входной файл - 80 MiB, получим 11 блоков: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10 и 1 MiB. В многопоточном режиме размеры блоков хранятся в заголовках блоков. Это не делается в однопоточном режиме, поэтому закодированный вывод не будет идентичен тому, что в многопоточном режиме. --flush-timeout=timeout При сжатии, если прошло более timeout миллисекунд (положительное целое число) с предыдущего сброса и чтение дополнительного входа заблокировано, все ожидающие входные данные сбрасываются из энкодера и становятся доступными в выходном потоке. Это может быть полезно, если xz используется для сжатия данных, которые передаются по сети. Малые значения timeout делают данные доступными на принимающем конце с малой задержкой, но большие значения дают лучшее соотношение сжатия. Эта функция отключена по умолчанию. Если эта опция указана несколько раз, последняя вступает в силу. Специальное значение timeout 0 может использоваться для явного отключения этой функции. Эта функция недоступна в не-POSIX-системах. Эта функция все еще экспериментальна. В настоящее время xz не подходит для распаковки потока в реальном времени из-за того, как xz выполняет буферизацию. --memlimit-compress=limit Установить лимит использования памяти для сжатия. Если эта опция указана несколько раз, последняя вступает в силу. Если настройки сжатия превышают лимит, xz попытается скорректировать настройки вниз, чтобы лимит больше не превышался, и выведет уведомление о том, что автоматическая корректировка была произведена. Корректировки производятся в следующем порядке: уменьшение количества потоков, переключение в однопоточный режим, если даже один поток в многопоточном режиме превышает лимит, и, наконец, уменьшение размера словаря LZMA2. При сжатии с --format=raw или если указан --no-adjust, может уменьшаться только количество потоков, поскольку это можно сделать без влияния на сжатый вывод. Если лимит невозможно соблюсти даже с корректировками, описанными выше, выводится ошибка и xz выходит с кодом выхода 1. Лимит можно указать несколькими способами: • Лимит может быть абсолютным значением в байтах. Использование целочисленного суффикса, такого как MiB, может быть полезным. Пример: --memlimit-compress=80MiB • Лимит может быть указан в процентах от общего физического объема памяти (ОЗУ). Это может быть полезно, особенно при установке переменной окружения XZ_DEFAULTS в скрипте инициализации оболочки, который делится между разными компьютерами. Таким образом лимит автоматически больше на системах с большим объемом памяти. Пример: --memlimit-compress=70% • Лимит можно сбросить до значения по умолчанию, установив его в 0. В настоящее время это эквивалентно установке лимита в max (нет лимита использования памяти). Для 32-разрядного xz есть специальный случай: если лимит будет больше 4020 MiB, лимит устанавливается в 4020 MiB. На MIPS32 вместо этого используется 2000 MiB. (Значения 0 и max не затрагиваются этим. Аналогичная функция не существует для распаковки.) Это может быть полезно, когда 32-разрядный исполняемый файл имеет доступ к адресу 4 GiB пространства (2 GiB на MIPS32), в то время как, надеюсь, не нанося вреда в других ситуациях. См. также раздел Memory usage. --memlimit-decompress=limit Установить лимит использования памяти для распаковки. Это также влияет на режим --list. Если операция невозможна без превышения лимита, xz выведет ошибку и распаковка файла не удастся. См. --memlimit-compress=limit для возможных способов указания лимита. --memlimit-mt-decompress=limit Установить лимит использования памяти для многопоточной распаковки. Это может влиять только на количество потоков; это никогда не заставит xz отказаться от распаковки файла. Если limit слишком низкий, чтобы позволить любое многопоточность, лимит игнорируется и xz продолжит в однопоточном режиме. Обратите внимание, что если также используется --memlimit-decompress, он всегда применяется как к однопоточному, так и к многопоточному режимам, поэтому эффективный лимит для многопоточности никогда не будет выше, чем лимит, установленный с --memlimit-decompress. В отличие от других опций лимита использования памяти, --memlimit-mt-decompress=limit имеет системно-специфическое значение лимита по умолчанию. xz --info-memory можно использовать для просмотра текущего значения. Эта опция и ее значение по умолчанию существуют, потому что без любого лимита потоковый декомпрессор может в конечном итоге выделить безумное количество памяти для некоторых входных файлов. Если значение лимита по умолчанию слишком низкое на вашей системе, не стесняйтесь увеличить лимит, но никогда не устанавливайте его в значение больше, чем объем используемой ОЗУ, поскольку с подходящими входными файлами xz попытается использовать это количество памяти даже с небольшим количеством потоков. Выход из памяти или подкачка не улучшит производительность распаковки. См. --memlimit-compress=limit для возможных способов указания лимита. Установка limit в 0 сбрасывает лимит до системно-специфического значения по умолчанию. -M limit, --memlimit=limit, --memory=limit Это эквивалентно указанию --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Выводить ошибку и выходить, если лимит использования памяти не может быть соблюден без корректировки настроек, влияющих на сжатый вывод. То есть, это предотвращает xz от переключения энкодера из многопоточного режима в однопоточный режим и от уменьшения размера словаря LZMA2. Даже при использовании этой опции количество потоков может быть уменьшено для соблюдения лимита использования памяти, поскольку это не повлияет на сжатый вывод. Автоматическая корректировка всегда отключена при создании необработанных потоков (--format=raw). -T threads, --threads=threads Указать количество рабочих потоков. Установка threads в специальное значение 0 заставляет xz использовать до такого количества потоков, сколько поддерживают процессор(ы) системы. Фактическое количество потоков может быть меньше threads, если входной файл недостаточно большой для потоков с заданными настройками или если использование большего количества потоков превысит лимит использования памяти. Однопоточный и многопоточный компрессоры производят разный вывод. Однопоточный компрессор даст самый маленький размер файла, но только вывод от многопоточного компрессора может быть распакован с использованием нескольких потоков. Установка threads в 1 использует однопоточный режим. Установка threads в любое другое значение, включая 0, использует многопоточный компрессор, даже если система поддерживает только один аппаратный поток. (xz 5.2.x использовал однопоточный режим в этой ситуации.) Для использования многопоточного режима с только одним потоком установите threads в +1. Префикс + не имеет эффекта с другими значениями. Лимит использования памяти все равно может заставить xz переключиться в однопоточный режим, если не используется --no-adjust. Поддержка префикса + была добавлена в xz 5.4.0. Если запрошено автоматическое количество потоков и не указан лимит использования памяти, то будет использоваться системно-специфическое значение мягкого лимита по умолчанию для возможного ограничения количества потоков. Это мягкий лимит в смысле, что он игнорируется, если количество потоков становится единицей, поэтому мягкий лимит никогда не остановит xz от сжатия или распаковки. Это значение мягкого лимита не заставит xz переключиться из многопоточного режима в однопоточный режим. Активные лимиты можно увидеть с xz --info-memory. В настоящее время единственный метод потоков - разделение входа на блоки и сжатие их независимо друг от друга. Размер блока по умолчанию зависит от уровня сжатия и может быть переопределен с помощью опции --block-size=size. Потоковая распаковка работает только на файлах, которые содержат несколько блоков с информацией о размере в заголовках блоков. Все достаточно большие файлы, сжатые в многопоточном режиме, удовлетворяют этому условию, но файлы, сжатые в однопоточном режиме, нет, даже если использовалась --block-size=size. Значение threads по умолчанию - 0. В xz 5.4.x и старше значение по умолчанию - 1. Custom compressor filter chains Пользовательская цепочка фильтров позволяет указывать настройки сжатия в деталях вместо использования настроек, связанных с пресетами. Когда указана пользовательская цепочка фильтров, опции пресетов (-0 ... -9 и --extreme), указанные ранее в командной строке, забываются. Если опция пресета указана после одной или более опций пользовательской цепочки фильтров, новый пресет вступает в силу, и пользовательские опции цепочки фильтров, указанные ранее, забываются. Цепочка фильтров сравнима с конвейером в командной строке. При сжатии несжатый вход передается первому фильтру, чей вывод передается следующему фильтру (если он есть). Вывод последнего фильтра записывается в сжатый файл. Максимальное количество фильтров в цепочке - четыре, но обычно цепочка фильтров имеет только один или два фильтра. Многие фильтры имеют ограничения на то, где они могут быть в цепочке фильтров: некоторые фильтры могут работать только как последний фильтр в цепочке, некоторые только как нефинальный фильтр, а некоторые работают в любой позиции в цепочке. В зависимости от фильтра это ограничение либо обусловлено дизайном фильтра, либо существует для предотвращения проблем безопасности. Пользовательскую цепочку фильтров можно указать двумя разными способами. Опции --filters=filters и --filters1=filters ... --filters9=filters позволяют указать всю цепочку фильтров в одной опции с использованием синтаксиса строки фильтров liblzma. В качестве альтернативы цепочку фильтров можно указать, используя одну или более отдельных опций фильтров в порядке, в котором они должны быть в цепочке фильтров. То есть, порядок отдельных опций фильтров имеет значение! При декодировании необработанных потоков (--format=raw) цепочка фильтров должна быть указана в том же порядке, в котором она была указана при сжатии. Любые отдельные опции фильтров или опции пресетов, указанные до полной опции цепочки (--filters=filters), будут забыты. Отдельные фильтры, указанные после полной опции цепочки, сбросят цепочку фильтров. Как полные, так и отдельные опции фильтров принимают опции, специфичные для фильтра, в виде списка, разделенного запятыми. Дополнительные запятые в опциях игнорируются. Каждая опция имеет значение по умолчанию, поэтому укажите только те, которые вы хотите изменить. Чтобы увидеть всю цепочку фильтров и опции, используйте xz -vv (то есть, используйте --verbose дважды). Это работает также для просмотра опций цепочки фильтров, используемых пресетами. --filters=filters Указать полную цепочку фильтров или пресет в одной опции. Каждый фильтр может быть разделен пробелами или двумя дефисами (--). filters может потребоваться заключить в кавычки в командной строке оболочки, чтобы она анализировалась как одна опция. Чтобы обозначить опции, используйте : или =. Пресет можно предварить - и за ним следовать нулю или более флагам. Единственный поддерживаемый флаг - e для применения тех же опций, что и --extreme. --filters1=filters ... --filters9=filters Указать до девяти дополнительных цепочек фильтров, которые можно использовать с --block-list. Например, при сжатии архива с исполняемыми файлами, за которыми следуют текстовые файлы, исполняемая часть может использовать цепочку фильтров с фильтром BCJ, а текстовая часть - только фильтр LZMA2. --filters-help Вывести справочное сообщение, описывающее, как указывать пресеты и пользовательские цепочки фильтров в опциях --filters и --filters1=filters ... --filters9=filters, и выйти успешно. --lzma1[=options] --lzma2[=options] Добавить фильтр LZMA1 или LZMA2 в цепочку фильтров. Эти фильтры могут использоваться только как последний фильтр в цепочке. LZMA1 - это устаревший фильтр, который поддерживается почти исключительно из-за устаревшего формата файла .lzma, который поддерживает только LZMA1. LZMA2 - это обновленная версия LZMA1 для устранения некоторых практических проблем LZMA1. Формат .xz использует LZMA2 и не поддерживает LZMA1. Скорость сжатия и соотношения LZMA1 и LZMA2 практически одинаковы. LZMA1 и LZMA2 делят один и тот же набор опций: preset=preset Сбросить все опции LZMA1 или LZMA2 на preset. Preset состоит из целого числа, за которым может следовать модификаторы пресета в виде одиночной буквы. Целое число может быть от 0 до 9, соответствующее опциям командной строки -0 ... -9. Единственный поддерживаемый модификатор - e, который соответствует --extreme. Если пресет не указан, значения опций LZMA1 или LZMA2 по умолчанию берутся из пресета 6. dict=size Размер словаря (буфера истории) указывает, сколько байт недавно обработанных несжатых данных хранится в памяти. Алгоритм пытается найти повторяющиеся последовательности байтов (совпадения) в несжатых данных и заменить их ссылками на данные, которые в настоящее время находятся в словаре. Чем больше словарь, тем выше шанс найти совпадение. Таким образом, увеличение размера словаря обычно улучшает коэффициент сжатия, но словарь больше, чем несжатый файл - трата памяти. Типичный размер словаря - от 64 KiB до 64 MiB. Минимум - 4 KiB. Максимум для сжатия в настоящее время 1.5 GiB (1536 MiB). Декомпрессор уже поддерживает словари до одного байта меньше 4 GiB, что является максимумом для форматов потоков LZMA1 и LZMA2. Размер словаря и поисковик совпадений (mf) вместе определяют использование памяти энкодером LZMA1 или LZMA2. Тот же (или больший) размер словаря требуется для распаковки, который использовался при сжатии, поэтому использование памяти декомпрессором определяется размером словаря, использованным при сжатии. Заголовки .xz хранят размер словаря либо как 2^n, либо как 2^n + 2^(n-1), так что эти размеры в некоторой степени предпочтительны для сжатия. Другие размеры будут округлены вверх при хранении в заголовках .xz. lc=lc Указать количество битов контекста литерала. Минимум - 0, максимум - 4; значение по умолчанию - 3. Кроме того, сумма lc и lp не должна превышать 4. Все байты, которые не могут быть закодированы как совпадения, кодируются как литералы. То есть, литералы - просто 8-битные байты, которые кодируются по одному. Литеральное кодирование предполагает, что высшие lc биты предыдущего несжатого байта коррелируют со следующим байтом. Например, в типичном английском тексте заглавная буква часто следует за строчной буквой, а строчная буква обычно следует за другой строчной буквой. В наборе символов US-ASCII высшие три бита - 010 для заглавных букв и 011 для строчных букв. Когда lc как минимум 3, литерное кодирование может использовать это свойство в несжатых данных. Значение по умолчанию (3) обычно хорошее. Если вы хотите максимальное сжатие, протестируйте lc=4. Иногда это немного помогает, а иногда ухудшает сжатие. Если ухудшает, протестируйте lc=2 тоже. lp=lp Указать количество битов позиции литерала. Минимум - 0, максимум - 4; значение по умолчанию - 0. lp влияет на то, какое выравнивание в несжатых данных предполагается при кодировании литералов. См. pb ниже для дополнительной информации о выравнивании. pb=pb Указать количество битов позиции. Минимум - 0, максимум - 4; значение по умолчанию - 2. pb влияет на то, какое выравнивание в несжатых данных предполагается в общем. Значение по умолчанию подразумевает четырехбайтовое выравнивание (2^pb=2^2=4), что часто бывает хорошим выбором, когда нет лучшей догадки. Когда выравнивание известно, установка pb соответственно может немного уменьшить размер файла. Например, для текстовых файлов с однобайтовым выравниванием (US-ASCII, ISO-8859-*, UTF-8), установка pb=0 может немного улучшить сжатие. Для текста UTF-16 pb=1 - хороший выбор. Если выравнивание - нечетное число, как 3 байта, pb=0 может быть лучшим выбором. Хотя предполагаемое выравнивание можно скорректировать с помощью pb и lp, LZMA1 и LZMA2 все равно немного предпочитают 16-байтовое выравнивание. Стоит учитывать это при проектировании форматов файлов, которые, вероятно, будут часто сжиматься с LZMA1 или LZMA2. mf=mf Поисковик совпадений сильно влияет на скорость энкодера, использование памяти и коэффициент сжатия. Обычно поисковики совпадений Hash Chain быстрее, чем Binary Tree. Значение по умолчанию зависит от пресета: 0 использует hc3, 1–3 используют hc4, а остальные - bt4. Поддерживаются следующие поисковики совпадений. Формулы использования памяти ниже - грубые приближения, которые ближе всего к реальности, когда dict - степень двойки. hc3 Hash Chain с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 7.5 (если dict <= 16 MiB); dict * 5.5 + 64 MiB (если dict > 16 MiB) hc4 Hash Chain с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 7.5 (если dict <= 32 MiB); dict * 6.5 (если dict > 32 MiB) bt2 Binary Tree с хэшированием 2-байтовым Минимальное значение для nice: 2 Использование памяти: dict * 9.5 bt3 Binary Tree с хэшированием 2- и 3-байтовым Минимальное значение для nice: 3 Использование памяти: dict * 11.5 (если dict <= 16 MiB); dict * 9.5 + 64 MiB (если dict > 16 MiB) bt4 Binary Tree с хэшированием 2-, 3- и 4-байтовым Минимальное значение для nice: 4 Использование памяти: dict * 11.5 (если dict <= 32 MiB); dict * 10.5 (если dict > 32 MiB) mode=mode Режим сжатия указывает метод анализа данных, производимых поисковиком совпадений. Поддерживаемые режимы - fast и normal. Значение по умолчанию - fast для пресетов 0–3 и normal для пресетов 4–9. Обычно fast используется с поисковиками совпадений Hash Chain, а normal - с Binary Tree. Это также то, что делают пресеты. nice=nice Указать, что считается хорошей длиной для совпадения. Как только найдено совпадение как минимум nice байт, алгоритм перестает искать возможные лучшие совпадения. nice может быть 2–273 байта. Более высокие значения склоняются к лучшему коэффициенту сжатия за счет скорости. Значение по умолчанию зависит от пресета. depth=depth Указать максимальную глубину поиска в поисковике совпадений. Значение по умолчанию - специальное значение 0, которое заставляет компрессор определять разумную глубину из mf и nice. Разумная глубина для Hash Chains - 4–100 и 16–1000 для Binary Trees. Использование очень высоких значений для depth может сделать энкодер чрезвычайно медленным для некоторых файлов. Избегайте установки depth больше 1000, если вы готовы прервать сжатие в случае, если оно занимает слишком много времени. При декодировании необработанных потоков (--format=raw), LZMA2 требуется только размер словаря. LZMA1 также требует lc, lp и pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Добавить фильтр ветвления/вызова/перехода (BCJ) в цепочку фильтров. Эти фильтры могут использоваться только как нефинальный фильтр в цепочке. Фильтр BCJ преобразует относительные адреса в машинном коде в их абсолютные аналоги. Это не изменяет размер данных, но увеличивает избыточность, что может помочь LZMA2 произвести 0–15% меньший файл .xz. Фильтры BCJ всегда обратимы, так что использование фильтра BCJ для неправильного типа данных не приведет к потере данных, хотя это может немного ухудшить коэффициент сжатия. Фильтры BCJ очень быстрые и используют незначительное количество памяти. У этих фильтров BCJ известны проблемы, связанные с коэффициентом сжатия: • Некоторые типы файлов, содержащие исполняемый код (например, объектные файлы, статические библиотеки и модули ядра Linux), имеют адреса в инструкциях, заполненные заполнителями. Эти фильтры BCJ все равно выполнят преобразование адреса, что сделает сжатие хуже для этих файлов. • Если фильтр BCJ применяется к архиву, возможно, что это сделает коэффициент сжатия хуже, чем без использования фильтра BCJ. Например, если в архиве есть похожие или даже идентичные исполняемые файлы, то фильтрация, вероятно, сделает файлы менее похожими, и, следовательно, сжатие хуже. Содержимое нефайловых файлов в том же архиве тоже может иметь значение. На практике нужно попробовать с фильтром BCJ и без него, чтобы увидеть, что лучше в каждой ситуации. Разные наборы инструкций имеют разное выравнивание: исполняемый файл должен быть выровнен по кратному этого значения во входных данных, чтобы фильтр работал. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit или 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Поскольку отфильтрованные данные BCJ обычно сжимаются с LZMA2, коэффициент сжатия может немного улучшиться, если опции LZMA2 установлены так, чтобы соответствовать выравниванию выбранного фильтра BCJ. Примеры: • Фильтр IA-64 имеет выравнивание 16 байт, так что pb=4,lp=4,lc=0 хорошо работает с LZMA2 (2^4=16). • Код RISC-V имеет выравнивание 2 или 4 байта в зависимости от того, содержит ли файл 16-битные сжатые инструкции (расширение C). При использовании 16-битных инструкций pb=2,lp=1,lc=3 или pb=1,lp=1,lc=3 хорошо работает. При отсутствии 16-битных инструкций pb=2,lp=2,lc=2 - лучшее. readelf -h можно использовать для проверки, появляется ли "RVC" в строке "Flags". • ARM64 всегда имеет выравнивание 4 байта, так что pb=2,lp=2,lc=2 - лучшее. • Фильтр x86 - исключение. Обычно хорошо придерживаться значений по умолчанию LZMA2 (pb=2,lp=0,lc=3) при сжатии исполняемых файлов x86. Все фильтры BCJ поддерживают одни и те же опции: start=offset Указать начальный смещение, которое используется при преобразовании между относительными и абсолютными адресами. Смещение должно быть кратным выравниванию фильтра (см. таблицу выше). Значение по умолчанию - ноль. На практике значение по умолчанию хорошее; указание пользовательского смещения почти никогда не бывает полезным. --delta[=options] Добавить фильтр Delta в цепочку фильтров. Фильтр Delta может использоваться только как нефинальный фильтр в цепочке. В настоящее время поддерживается только простое байтовое вычисление дельты. Это может быть полезно при сжатии, например, несжатых растровых изображений или несжатого PCM-аудио. Однако, специальные алгоритмы могут дать значительно лучшие результаты, чем Delta + LZMA2. Это верно, особенно для аудио, которое сжимается быстрее и лучше, например, с flac(1). Поддерживаемые опции: dist=distance Указать расстояние вычисления дельты в байтах. distance должно быть 1–256. Значение по умолчанию - 1. Например, с dist=2 и входом из восьми байт A1 B1 A2 B3 A3 B5 A4 B7 вывод будет A1 B1 01 02 01 02 01 02. Other options -q, --quiet Подавлять предупреждения и уведомления. Укажите это дважды, чтобы подавить ошибки тоже. Эта опция не влияет на код выхода. То есть, даже если предупреждение было подавлено, код выхода для указания предупреждения все равно используется. -v, --verbose Быть подробным. Если стандартный вывод ошибок подключен к терминалу, xz отобразит индикатор прогресса. Указание --verbose дважды даст еще более подробный вывод. Индикатор прогресса показывает следующую информацию: • Процент завершения отображается, если размер входного файла известен. То есть, процент не может быть показан в конвейерах. • Количество сжатых данных, произведенных (при сжатии) или потребленных (при распаковке). • Количество несжатых данных, потребленных (при сжатии) или произведенных (при распаковке). • Коэффициент сжатия, который рассчитывается путем деления количества обработанных сжатых данных на количество обработанных несжатых данных. • Скорость сжатия или распаковки. Это измеряется как количество несжатых данных, потребленных (сжатие) или произведенных (распаковка) в секунду. Она отображается после того, как прошло несколько секунд с момента запуска xz обработки файла. • Прошедшее время в формате M:SS или H:MM:SS. • Оставшееся оценочное время отображается только в том случае, если размер входного файла известен и прошло пару секунд с момента запуска xz обработки файла. Время отображается в менее точном формате, который никогда не имеет двоеточий, например, 2 min 30 s. Когда стандартный вывод ошибок не является терминалом, --verbose заставит xz выводить имя файла, сжатый размер, несжатый размер, коэффициент сжатия и, возможно, скорость и прошедшее время в одну строку в стандартный вывод ошибок после сжатия или распаковки файла. Скорость и прошедшее время включаются только в том случае, если операция заняла хотя бы несколько секунд. Если операция не завершилась, например, из-за прерывания пользователем, также выводится процент завершения, если размер входного файла известен. -Q, --no-warn Не устанавливать код выхода в 2, даже если обнаружено условие, заслуживающее предупреждения. Эта опция не влияет на уровень подробности, поэтому для того, чтобы не отображать предупреждения и не изменять код выхода, нужно использовать как --quiet, так и --no-warn. --robot Выводить сообщения в машинно-анализируемом формате. Это предназначено для облегчения написания фронтендов, которые хотят использовать xz вместо liblzma, что может быть в случае с различными скриптами. Вывод с этой опцией включенной предназначен для стабильности между релизами xz. См. раздел ROBOT MODE для деталей. --info-memory Вывести в удобочитаемом формате, сколько физической памяти (ОЗУ) и сколько процессорных потоков, по мнению xz, имеет система, и лимиты использования памяти для сжатия и распаковки, и выйти успешно. -h, --help Вывести справочное сообщение, описывающее наиболее часто используемые опции, и выйти успешно. -H, --long-help Вывести справочное сообщение, описывающее все функции xz, и выйти успешно -V, --version Вывести номер версии xz и liblzma в удобочитаемом формате. Для получения машинно-анализируемого вывода укажите --robot перед --version. ROBOT MODE Режим робота активируется с опцией --robot. Он делает вывод xz легче для разбора другими программами. В настоящее время --robot поддерживается только вместе с --list, --filters-help, --info-memory и --version. В будущем он будет поддерживаться для сжатия и распаковки. List mode xz --robot --list использует вывод, разделенный табуляцией. Первый столбец каждой строки содержит строку, которая указывает тип информации, найденной в этой строке: name Это всегда первая строка при начале списка файла. Второй столбец на строке - имя файла. file Эта строка содержит общую информацию о файле .xz. Эта строка всегда печатается после строки name. stream Эта строка используется только если указан --verbose. Здесь столько строк stream, сколько потоков в файле .xz. block Эта строка используется только если указан --verbose. Здесь столько строк block, сколько блоков в файле .xz. Строки block отображаются после всех строк stream; разные типы строк не перемежаются. summary Этот тип строки используется только если указан --verbose дважды. Эта строка печатается после всех строк block. Как и строка file, строка summary содержит общую информацию о файле .xz. totals Эта строка всегда последняя строка вывода списка. Она показывает общие счетчики и размеры. Столбцы строк file: 2. Количество потоков в файле 3. Общее количество блоков в потоке(ах) 4. Сжатый размер файла 5. Несжатый размер файла 6. Коэффициент сжатия, например, 0.123. Если коэффициент больше 9.999, отображаются три дефиса (---) вместо коэффициента. 7. Список имен проверок целостности, разделенный запятыми. Следующие строки используются для известных типов проверок: None, CRC32, CRC64 и SHA-256. Для неизвестных типов проверок используется Unknown-N, где N - ID проверки в виде десятичного числа (одна или две цифры). 8. Общий размер заполнения потока в файле Столбцы строк stream: 2. Номер потока (первый поток - 1) 3. Количество блоков в потоке 4. Сжатый начальный смещение 5. Несжатый начальный смещение 6. Сжатый размер (не включает заполнение потока) 7. Несжатый размер 8. Коэффициент сжатия 9. Имя проверки целостности 10. Размер заполнения потока Столбцы строк block: 2. Номер потока, содержащего этот блок 3. Номер блока относительно начала потока (первый блок - 1) 4. Номер блока относительно начала файла 5. Сжатый начальный смещение относительно начала файла 6. Несжатый начальный смещение относительно начала файла 7. Общий сжатый размер блока (включает заголовки) 8. Несжатый размер 9. Коэффициент сжатия 10. Имя проверки целостности Если указан --verbose дважды, в строках block добавляются дополнительные столбцы. Эти не отображаются с одним --verbose, потому что получение этой информации требует многих поисков и, следовательно, может быть медленно: 11. Значение проверки целостности в шестнадцатеричном формате 12. Размер заголовка блока 13. Флаги блока: c указывает, что сжатый размер присутствует, а u указывает, что несжатый размер присутствует. Если флаг не установлен, отображается дефис (-) для сохранения длины строки фиксированной. Новые флаги могут быть добавлены в конец строки в будущем. 14. Размер фактических сжатых данных в блоке (это исключает заголовок блока, заполнение блока и поля проверки) 15. Количество памяти (в байтах), необходимое для распаковки этого блока с этой версией xz 16. Цепочка фильтров. Обратите внимание, что большинство опций, использованных во время сжатия, не могут быть известны, потому что только опции, необходимые для распаковки, хранятся в заголовках .xz. Столбцы строк summary: 2. Количество памяти (в байтах), необходимое для распаковки этого файла с этой версией xz 3. yes или no, указывающее, имеют ли все заголовки блоков как сжатый размер, так и несжатый размер, хранящиеся в них С версии xz 5.1.2alpha: 4. Минимальная версия xz, необходимая для распаковки файла Столбцы строки totals: 2. Количество потоков 3. Количество блоков 4. Сжатый размер 5. Несжатый размер 6. Средний коэффициент сжатия 7. Список имен проверок целостности, которые присутствовали в файлах, разделенный запятыми 8. Размер заполнения потока 9. Количество файлов. Это здесь, чтобы сохранить порядок предыдущих столбцов таким же, как в строках file. Если указан --verbose дважды, в строке totals добавляются дополнительные столбцы: 10. Максимальное количество памяти (в байтах), необходимое для распаковки файлов с этой версией xz 11. yes или no, указывающее, имеют ли все заголовки блоков как сжатый размер, так и несжатый размер, хранящиеся в них С версии xz 5.1.2alpha: 12. Минимальная версия xz, необходимая для распаковки файла Будущие версии могут добавить новые типы строк, и новые столбцы могут быть добавлены к существующим типам строк, но существующие столбцы не будут изменены. Filters help xz --robot --filters-help выводит поддерживаемые фильтры в следующем формате: filter:option=<value>,option=<value>... filter Name of the filter option Name of a filter specific option value Numeric value ranges appear as <min-max>. String value choices are shown within < > and separated by a | character. Каждый фильтр выводится на своей строке. Memory limit information xz --robot --info-memory выводит одну строку с несколькими столбцами, разделенными табуляцией: 1. Total amount of physical memory (RAM) in bytes. 2. Memory usage limit for compression in bytes (--memlimit-compress). A special value of 0 indicates the default setting which for sin‐ gle-threaded mode is the same as no limit. 3. Memory usage limit for decompression in bytes (--memlimit-decom‐ press). A special value of 0 indicates the default setting which for single-threaded mode is the same as no limit. 4. Since xz 5.3.4alpha: Memory usage for multi-threaded decompression in bytes (--memlimit-mt-decompress). This is never zero because a system-specific default value shown in the column 5 is used if no limit has been specified explicitly. This is also never greater than the value in the column 3 even if a larger value has been specified with --memlimit-mt-decompress. 5. Since xz 5.3.4alpha: A system-specific default memory usage limit that is used to limit the number of threads when compressing with an automatic number of threads (--threads=0) and no memory usage limit has been specified (--memlimit-compress). This is also used as the default value for --memlimit-mt-decompress. 6. Since xz 5.3.4alpha: Number of available processor threads. In the future, the output of xz --robot --info-memory may have more columns, but never more than a single line. Version xz --robot --version prints the version number of xz and liblzma in the following format: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Major version. YYY Minor version. Even numbers are stable. Odd numbers are alpha or beta versions. ZZZ Patch level for stable releases or just a counter for develop‐ ment releases. S Stability. 0 is alpha, 1 is beta, and 2 is stable. S should be always 2 when YYY is even. XYYYZZZS are the same on both lines if xz and liblzma are from the same XZ Utils release. Examples: 4.999.9beta is 49990091 and 5.0.0 is 50000002. EXIT STATUS 0 All is good. 1 An error occurred. 2 Something worth a warning occurred, but no actual errors oc‐ curred. Notices (not warnings or errors) printed on standard error don't affect the exit status. ENVIRONMENT xz parses space-separated lists of options from the environment vari‐ ables XZ_DEFAULTS and XZ_OPT, in this order, before parsing the options from the command line. Note that only options are parsed from the en‐ vironment variables; all non-options are silently ignored. Parsing is done with getopt_long(3) which is used also for the command line argu‐ ments. XZ_DEFAULTS User-specific or system-wide default options. Typically this is set in a shell initialization script to enable xz's memory usage limiter by default. Excluding shell initialization scripts and similar special cases, scripts must never set or unset XZ_DE‐ FAULTS. XZ_OPT This is for passing options to xz when it is not possible to set the options directly on the xz command line. This is the case when xz is run by a script or tool, for example, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Scripts may use XZ_OPT, for example, to set script-specific de‐ fault compression options. It is still recommended to allow users to override XZ_OPT if that is reasonable. For example, in sh(1) scripts one may use something like this: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY The command line syntax of xz is practically a superset of lzma, un‐ lzma, and lzcat as found from LZMA Utils 4.32.x. In most cases, it is possible to replace LZMA Utils with XZ Utils without breaking existing scripts. There are some incompatibilities though, which may sometimes cause problems. Compression preset levels The numbering of the compression level presets is not identical in xz and LZMA Utils. The most important difference is how dictionary sizes are mapped to different presets. Dictionary size is roughly equal to the decompressor memory usage. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB The dictionary size differences affect the compressor memory usage too, but there are some other differences between LZMA Utils and XZ Utils, which make the difference even bigger: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB The default preset level in LZMA Utils is -7 while in XZ Utils it is -6, so both use an 8 MiB dictionary by default. Streamed vs. non-streamed .lzma files The uncompressed size of the file can be stored in the .lzma header. LZMA Utils does that when compressing regular files. The alternative is to mark that uncompressed size is unknown and use end-of-payload marker to indicate where the decompressor should stop. LZMA Utils uses this method when uncompressed size isn't known, which is the case, for example, in pipes. xz supports decompressing .lzma files with or without end-of-payload marker, but all .lzma files created by xz will use end-of-payload marker and have uncompressed size marked as unknown in the .lzma header. This may be a problem in some uncommon situations. For exam‐ ple, a .lzma decompressor in an embedded device might work only with files that have known uncompressed size. If you hit this problem, you need to use LZMA Utils or LZMA SDK to create .lzma files with known un‐ compressed size. Unsupported .lzma files The .lzma format allows lc values up to 8, and lp values up to 4. LZMA Utils can decompress files with any lc and lp, but always creates files with lc=3 and lp=0. Creating files with other lc and lp is possible with xz and with LZMA SDK. The implementation of the LZMA1 filter in liblzma requires that the sum of lc and lp must not exceed 4. Thus, .lzma files, which exceed this limitation, cannot be decompressed with xz. LZMA Utils creates only .lzma files which have a dictionary size of 2^n (a power of 2) but accepts files with any dictionary size. liblzma ac‐ cepts only .lzma files which have a dictionary size of 2^n or 2^n + 2^(n-1). This is to decrease false positives when detecting .lzma files. These limitations shouldn't be a problem in practice, since practically all .lzma files have been compressed with settings that liblzma will accept. Trailing garbage When decompressing, LZMA Utils silently ignore everything after the first .lzma stream. In most situations, this is a bug. This also means that LZMA Utils don't support decompressing concatenated .lzma files. If there is data left after the first .lzma stream, xz considers the file to be corrupt unless --single-stream was used. This may break ob‐ scure scripts which have assumed that trailing garbage is ignored. NOTES Compressed output may vary The exact compressed output produced from the same uncompressed input file may vary between XZ Utils versions even if compression options are identical. This is because the encoder can be improved (faster or bet‐ ter compression) without affecting the file format. The output can vary even between different builds of the same XZ Utils version, if different build options are used. The above means that once --rsyncable has been implemented, the result‐ ing files won't necessarily be rsyncable unless both old and new files have been compressed with the same xz version. This problem can be fixed if a part of the encoder implementation is frozen to keep rsynca‐ ble output stable across xz versions. Embedded .xz decompressors Embedded .xz decompressor implementations like XZ Embedded don't neces‐ sarily support files created with integrity check types other than none and crc32. Since the default is --check=crc64, you must use --check=none or --check=crc32 when creating files for embedded systems. Outside embedded systems, all .xz format decompressors support all the check types, or at least are able to decompress the file without veri‐ fying the integrity check if the particular check is not supported. XZ Embedded supports BCJ filters, but only with the default start off‐ set. EXAMPLES Basics Compress the file foo into foo.xz using the default compression level (-6), and remove foo if compression is successful: xz foo Decompress bar.xz into bar and don't remove bar.xz even if decompres‐ sion is successful: xz -dk bar.xz Create baz.tar.xz with the preset -4e (-4 --extreme), which is slower than the default -6, but needs less memory for compression and decom‐ pression (48 MiB and 5 MiB, respectively): tar cf - baz | xz -4e > baz.tar.xz A mix of compressed and uncompressed files can be decompressed to stan‐ dard output with a single command: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Parallel compression of many files On GNU and *BSD, find(1) and xargs(1) can be used to parallelize com‐ pression of many files: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 The -P option to xargs(1) sets the number of parallel xz processes. The best value for the -n option depends on how many files there are to be compressed. If there are only a couple of files, the value should probably be 1; with tens of thousands of files, 100 or even more may be appropriate to reduce the number of xz processes that xargs(1) will eventually create. The option -T1 for xz is there to force it to single-threaded mode, be‐ cause xargs(1) is used to control the amount of parallelization. Robot mode Calculate how many bytes have been saved in total after compressing multiple files: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' A script may want to know that it is using new enough xz. The follow‐ ing sh(1) script checks that the version number of the xz tool is at least 5.0.0. This method is compatible with old beta versions, which didn't support the --robot option: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Set a memory usage limit for decompression using XZ_OPT, but if a limit has already been set, don't increase it: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Custom compressor filter chains The simplest use for custom filter chains is customizing a LZMA2 pre‐ set. This can be useful, because the presets cover only a subset of the potentially useful combinations of compression settings. The CompCPU columns of the tables from the descriptions of the options -0 ... -9 and --extreme are useful when customizing LZMA2 presets. Here are the relevant parts collected from those two tables: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 If you know that a file requires somewhat big dictionary (for example, 32 MiB) to compress well, but you want to compress it quicker than xz -8 would do, a preset with a low CompCPU value (for example, 1) can be modified to use a bigger dictionary: xz --lzma2=preset=1,dict=32MiB foo.tar With certain files, the above command may be faster than xz -6 while compressing significantly better. However, it must be emphasized that only some files benefit from a big dictionary while keeping the CompCPU value low. The most obvious situation, where a big dictionary can help a lot, is an archive containing very similar files of at least a few megabytes each. The dictionary size has to be significantly bigger than any individual file to allow LZMA2 to take full advantage of the similarities between consecutive files. If very high compressor and decompressor memory usage is fine, and the file being compressed is at least several hundred megabytes, it may be useful to use an even bigger dictionary than the 64 MiB that xz -9 would use: xz -vv --lzma2=dict=192MiB big_foo.tar Using -vv (--verbose --verbose) like in the above example can be useful to see the memory requirements of the compressor and decompressor. Re‐ member that using a dictionary bigger than the size of the uncompressed file is waste of memory, so the above command isn't useful for small files. Sometimes the compression time doesn't matter, but the decompressor memory usage has to be kept low, for example, to make it possible to decompress the file on an embedded system. The following command uses -6e (-6 --extreme) as a base and sets the dictionary to only 64 KiB. The resulting file can be decompressed with XZ Embedded (that's why there is --check=crc32) using about 100 KiB of memory. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo If you want to squeeze out as many bytes as possible, adjusting the number of literal context bits (lc) and number of position bits (pb) can sometimes help. Adjusting the number of literal position bits (lp) might help too, but usually lc and pb are more important. For example, a source code archive contains mostly US-ASCII text, so something like the following might give slightly (like 0.1 %) smaller file than xz -6e (try also without lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Using another filter together with LZMA2 can improve compression with certain file types. For example, to compress a x86-32 or x86-64 shared library using the x86 BCJ filter: xz --x86 --lzma2 libfoo.so Note that the order of the filter options is significant. If --x86 is specified after --lzma2, xz will give an error, because there cannot be any filter after LZMA2, and also because the x86 BCJ filter cannot be used as the last filter in the chain. The Delta filter together with LZMA2 can give good results with bitmap images. It should usually beat PNG, which has a few more advanced fil‐ ters than simple delta but uses Deflate for the actual compression. The image has to be saved in uncompressed format, for example, as un‐ compressed TIFF. The distance parameter of the Delta filter is set to match the number of bytes per pixel in the image. For example, 24-bit RGB bitmap needs dist=3, and it is also good to pass pb=0 to LZMA2 to accommodate the three-byte alignment: xz --delta=dist=3 --lzma2=pb=0 foo.tiff If multiple images have been put into a single archive (for example, .tar), the Delta filter will work on that too as long as all images have the same number of bytes per pixel. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html>
XZ(1) XZ Utils XZ(1) NAME xz, unxz, xzcat, lzma, unlzma, lzcat - Compress or decompress .xz and .lzma files SYNOPSIS xz [option...] [file...] COMMAND ALIASES unxz is equivalent to xz --decompress. xzcat is equivalent to xz --decompress --stdout. lzma is equivalent to xz --format=lzma. unlzma is equivalent to xz --format=lzma --decompress. lzcat is equivalent to xz --format=lzma --decompress --stdout. When writing scripts that need to decompress files, it is recommended to always use the name xz with appropriate arguments (xz -d or xz -dc) instead of the names unxz and xzcat. DESCRIPTION xz is a general-purpose data compression tool with command line syntax similar to gzip(1) and bzip2(1). The native file format is the .xz format, but the legacy .lzma format used by LZMA Utils and raw com‐ pressed streams with no container format headers are also supported. In addition, decompression of the .lz format used by lzip is supported. xz compresses or decompresses each file according to the selected oper‐ ation mode. If no files are given or file is -, xz reads from standard input and writes the processed data to standard output. xz will refuse (display an error and skip the file) to write compressed data to stan‐ dard output if it is a terminal. Similarly, xz will refuse to read compressed data from standard input if it is a terminal. Unless --stdout is specified, files other than - are written to a new file whose name is derived from the source file name: • When compressing, the suffix of the target file format (.xz or .lzma) is appended to the source filename to get the target file‐ name. • When decompressing, the .xz, .lzma, or .lz suffix is removed from the filename to get the target filename. xz also recognizes the suffixes .txz and .tlz, and replaces them with the .tar suffix. If the target file already exists, an error is displayed and the file is skipped. Unless writing to standard output, xz will display a warning and skip the file if any of the following applies: • File is not a regular file. Symbolic links are not followed, and thus they are not considered to be regular files. • File has more than one hard link. • File has setuid, setgid, or sticky bit set. • The operation mode is set to compress and the file already has a suffix of the target file format (.xz or .txz when compressing to the .xz format, and .lzma or .tlz when compressing to the .lzma for‐ mat). • The operation mode is set to decompress and the file doesn't have a suffix of any of the supported file formats (.xz, .txz, .lzma, .tlz, or .lz). After successfully compressing or decompressing the file, xz copies the owner, group, permissions, access time, and modification time from the source file to the target file. If copying the group fails, the per‐ missions are modified so that the target file doesn't become accessible to users who didn't have permission to access the source file. xz doesn't support copying other metadata like access control lists or ex‐ tended attributes yet. Once the target file has been successfully closed, the source file is removed unless --keep was specified. The source file is never removed if the output is written to standard output or if an error occurs. Sending SIGINFO or SIGUSR1 to the xz process makes it print progress information to standard error. This has only limited use since when standard error is a terminal, using --verbose will display an automati‐ cally updating progress indicator. Memory usage The memory usage of xz varies from a few hundred kilobytes to several gigabytes depending on the compression settings. The settings used when compressing a file determine the memory requirements of the decom‐ pressor. Typically the decompressor needs 5 % to 20 % of the amount of memory that the compressor needed when creating the file. For example, decompressing a file created with xz -9 currently requires 65 MiB of memory. Still, it is possible to have .xz files that require several gigabytes of memory to decompress. Especially users of older systems may find the possibility of very large memory usage annoying. To prevent uncomfortable surprises, xz has a built-in memory usage limiter, which is disabled by default. While some operating systems provide ways to limit the memory usage of processes, relying on it wasn't deemed to be flexible enough (for exam‐ ple, using ulimit(1) to limit virtual memory tends to cripple mmap(2)). The memory usage limiter can be enabled with the command line option --memlimit=limit. Often it is more convenient to enable the limiter by default by setting the environment variable XZ_DEFAULTS, for example, XZ_DEFAULTS=--memlimit=150MiB. It is possible to set the limits sepa‐ rately for compression and decompression by using --memlimit-com‐ press=limit and --memlimit-decompress=limit. Using these two options outside XZ_DEFAULTS is rarely useful because a single run of xz cannot do both compression and decompression and --memlimit=limit (or -M limit) is shorter to type on the command line. If the specified memory usage limit is exceeded when decompressing, xz will display an error and decompressing the file will fail. If the limit is exceeded when compressing, xz will try to scale the settings down so that the limit is no longer exceeded (except when using --for‐ mat=raw or --no-adjust). This way the operation won't fail unless the limit is very small. The scaling of the settings is done in steps that don't match the compression level presets, for example, if the limit is only slightly less than the amount required for xz -9, the settings will be scaled down only a little, not all the way down to xz -8. Concatenation and padding with .xz files It is possible to concatenate .xz files as is. xz will decompress such files as if they were a single .xz file. It is possible to insert padding between the concatenated parts or af‐ ter the last part. The padding must consist of null bytes and the size of the padding must be a multiple of four bytes. This can be useful, for example, if the .xz file is stored on a medium that measures file sizes in 512-byte blocks. Concatenation and padding are not allowed with .lzma files or raw streams. OPTIONS Integer suffixes and special values In most places where an integer argument is expected, an optional suf‐ fix is supported to easily indicate large integers. There must be no space between the integer and the suffix. KiB Multiply the integer by 1,024 (2^10). Ki, k, kB, K, and KB are accepted as synonyms for KiB. MiB Multiply the integer by 1,048,576 (2^20). Mi, m, M, and MB are accepted as synonyms for MiB. GiB Multiply the integer by 1,073,741,824 (2^30). Gi, g, G, and GB are accepted as synonyms for GiB. The special value max can be used to indicate the maximum integer value supported by the option. Operation mode If multiple operation mode options are given, the last one takes ef‐ fect. -z, --compress Compress. This is the default operation mode when no operation mode option is specified and no other operation mode is implied from the command name (for example, unxz implies --decompress). After successful compression, the source file is removed unless writing to standard output or --keep was specified. -d, --decompress, --uncompress Decompress. After successful decompression, the source file is removed unless writing to standard output or --keep was speci‐ fied. -t, --test Test the integrity of compressed files. This option is equiva‐ lent to --decompress --stdout except that the decompressed data is discarded instead of being written to standard output. No files are created or removed. -l, --list Print information about compressed files. No uncompressed out‐ put is produced, and no files are created or removed. In list mode, the program cannot read the compressed data from standard input or from other unseekable sources. The default listing shows basic information about files, one file per line. To get more detailed information, use also the --verbose option. For even more information, use --verbose twice, but note that this may be slow, because getting all the extra information requires many seeks. The width of verbose output exceeds 80 characters, so piping the output to, for exam‐ ple, less -S may be convenient if the terminal isn't wide enough. The exact output may vary between xz versions and different lo‐ cales. For machine-readable output, --robot --list should be used. Operation modifiers -k, --keep Don't delete the input files. Since xz 5.2.6, this option also makes xz compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. In earlier versions this was only done with --force. -f, --force This option has several effects: • If the target file already exists, delete it before compress‐ ing or decompressing. • Compress or decompress even if the input is a symbolic link to a regular file, has more than one hard link, or has the setuid, setgid, or sticky bit set. The setuid, setgid, and sticky bits are not copied to the target file. • When used with --decompress --stdout and xz cannot recognize the type of the source file, copy the source file as is to standard output. This allows xzcat --force to be used like cat(1) for files that have not been compressed with xz. Note that in future, xz might support new compressed file formats, which may make xz decompress more types of files instead of copying them as is to standard output. --format=format can be used to restrict xz to decompress only a single file for‐ mat. -c, --stdout, --to-stdout Write the compressed or decompressed data to standard output in‐ stead of a file. This implies --keep. --single-stream Decompress only the first .xz stream, and silently ignore possi‐ ble remaining input data following the stream. Normally such trailing garbage makes xz display an error. xz never decompresses more than one stream from .lzma files or raw streams, but this option still makes xz ignore the possible trailing data after the .lzma file or raw stream. This option has no effect if the operation mode is not --decom‐ press or --test. --no-sparse Disable creation of sparse files. By default, if decompressing into a regular file, xz tries to make the file sparse if the de‐ compressed data contains long sequences of binary zeros. It also works when writing to standard output as long as standard output is connected to a regular file and certain additional conditions are met to make it safe. Creating sparse files may save disk space and speed up the decompression by reducing the amount of disk I/O. -S .suf, --suffix=.suf When compressing, use .suf as the suffix for the target file in‐ stead of .xz or .lzma. If not writing to standard output and the source file already has the suffix .suf, a warning is dis‐ played and the file is skipped. When decompressing, recognize files with the suffix .suf in ad‐ dition to files with the .xz, .txz, .lzma, .tlz, or .lz suffix. If the source file has the suffix .suf, the suffix is removed to get the target filename. When compressing or decompressing raw streams (--format=raw), the suffix must always be specified unless writing to standard output, because there is no default suffix for raw streams. --files[=file] Read the filenames to process from file; if file is omitted, filenames are read from standard input. Filenames must be ter‐ minated with the newline character. A dash (-) is taken as a regular filename; it doesn't mean standard input. If filenames are given also as command line arguments, they are processed be‐ fore the filenames read from file. --files0[=file] This is identical to --files[=file] except that each filename must be terminated with the null character. Basic file format and compression options -F format, --format=format Specify the file format to compress or decompress: auto This is the default. When compressing, auto is equiva‐ lent to xz. When decompressing, the format of the input file is automatically detected. Note that raw streams (created with --format=raw) cannot be auto-detected. xz Compress to the .xz file format, or accept only .xz files when decompressing. lzma, alone Compress to the legacy .lzma file format, or accept only .lzma files when decompressing. The alternative name alone is provided for backwards compatibility with LZMA Utils. lzip Accept only .lz files when decompressing. Compression is not supported. The .lz format version 0 and the unextended version 1 are supported. Version 0 files were produced by lzip 1.3 and older. Such files aren't common but may be found from file archives as a few source packages were released in this format. People might have old personal files in this format too. Decompression support for the format version 0 was removed in lzip 1.18. lzip 1.4 and later create files in the format version 1. The sync flush marker extension to the format version 1 was added in lzip 1.6. This extension is rarely used and isn't supported by xz (diagnosed as corrupt input). raw Compress or uncompress a raw stream (no headers). This is meant for advanced users only. To decode raw streams, you need use --format=raw and explicitly specify the fil‐ ter chain, which normally would have been stored in the container headers. -C check, --check=check Specify the type of the integrity check. The check is calcu‐ lated from the uncompressed data and stored in the .xz file. This option has an effect only when compressing into the .xz format; the .lzma format doesn't support integrity checks. The integrity check (if any) is verified when the .xz file is decom‐ pressed. Supported check types: none Don't calculate an integrity check at all. This is usu‐ ally a bad idea. This can be useful when integrity of the data is verified by other means anyway. crc32 Calculate CRC32 using the polynomial from IEEE-802.3 (Ethernet). crc64 Calculate CRC64 using the polynomial from ECMA-182. This is the default, since it is slightly better than CRC32 at detecting damaged files and the speed difference is neg‐ ligible. sha256 Calculate SHA-256. This is somewhat slower than CRC32 and CRC64. Integrity of the .xz headers is always verified with CRC32. It is not possible to change or disable it. --ignore-check Don't verify the integrity check of the compressed data when de‐ compressing. The CRC32 values in the .xz headers will still be verified normally. Do not use this option unless you know what you are doing. Pos‐ sible reasons to use this option: • Trying to recover data from a corrupt .xz file. • Speeding up decompression. This matters mostly with SHA-256 or with files that have compressed extremely well. It's rec‐ ommended to not use this option for this purpose unless the file integrity is verified externally in some other way. -0 ... -9 Select a compression preset level. The default is -6. If mul‐ tiple preset levels are specified, the last one takes effect. If a custom filter chain was already specified, setting a com‐ pression preset level clears the custom filter chain. The differences between the presets are more significant than with gzip(1) and bzip2(1). The selected compression settings determine the memory requirements of the decompressor, thus us‐ ing a too high preset level might make it painful to decompress the file on an old system with little RAM. Specifically, it's not a good idea to blindly use -9 for everything like it often is with gzip(1) and bzip2(1). -0 ... -3 These are somewhat fast presets. -0 is sometimes faster than gzip -9 while compressing much better. The higher ones often have speed comparable to bzip2(1) with compa‐ rable or better compression ratio, although the results depend a lot on the type of data being compressed. -4 ... -6 Good to very good compression while keeping decompressor memory usage reasonable even for old systems. -6 is the default, which is usually a good choice for distributing files that need to be decompressible even on systems with only 16 MiB RAM. (-5e or -6e may be worth considering too. See --extreme.) -7 ... -9 These are like -6 but with higher compressor and decom‐ pressor memory requirements. These are useful only when compressing files bigger than 8 MiB, 16 MiB, and 32 MiB, respectively. On the same hardware, the decompression speed is approximately a constant number of bytes of compressed data per second. In other words, the better the compression, the faster the decom‐ pression will usually be. This also means that the amount of uncompressed output produced per second can vary a lot. The following table summarises the features of the presets: tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0;256 KiB;0;3 MiB;1 MiB -1;1 MiB;1;9 MiB;2 MiB -2;2 MiB;2;17 MiB;3 MiB -3;4 MiB;3;32 MiB;5 MiB -4;4 MiB;4;48 MiB;5 MiB -5;8 MiB;5;94 MiB;9 MiB -6;8 MiB;6;94 MiB;9 MiB -7;16 MiB;6;186 MiB;17 MiB -8;32 MiB;6;370 MiB;33 MiB -9;64 MiB;6;674 MiB;65 MiB Column descriptions: • DictSize is the LZMA2 dictionary size. It is waste of memory to use a dictionary bigger than the size of the uncompressed file. This is why it is good to avoid using the presets -7 ... -9 when there's no real need for them. At -6 and lower, the amount of memory wasted is usually low enough to not mat‐ ter. • CompCPU is a simplified representation of the LZMA2 settings that affect compression speed. The dictionary size affects speed too, so while CompCPU is the same for levels -6 ... -9, higher levels still tend to be a little slower. To get even slower and thus possibly better compression, see --extreme. • CompMem contains the compressor memory requirements in the single-threaded mode. It may vary slightly between xz ver‐ sions. • DecMem contains the decompressor memory requirements. That is, the compression settings determine the memory require‐ ments of the decompressor. The exact decompressor memory us‐ age is slightly more than the LZMA2 dictionary size, but the values in the table have been rounded up to the next full MiB. Memory requirements of the multi-threaded mode are significantly higher than that of the single-threaded mode. With the default value of --block-size, each thread needs 3*3*DictSize plus Comp‐ Mem or DecMem. For example, four threads with preset -6 needs 660–670 MiB of memory. -e, --extreme Use a slower variant of the selected compression preset level (-0 ... -9) to hopefully get a little bit better compression ra‐ tio, but with bad luck this can also make it worse. Decompres‐ sor memory usage is not affected, but compressor memory usage increases a little at preset levels -0 ... -3. Since there are two presets with dictionary sizes 4 MiB and 8 MiB, the presets -3e and -5e use slightly faster settings (lower CompCPU) than -4e and -6e, respectively. That way no two presets are identical. tab(;); c c c c c n n n n n. Preset;DictSize;Com‐ pCPU;CompMem;DecMem -0e;256 KiB;8;4 MiB;1 MiB -1e;1 MiB;8;13 MiB;2 MiB -2e;2 MiB;8;25 MiB;3 MiB -3e;4 MiB;7;48 MiB;5 MiB -4e;4 MiB;8;48 MiB;5 MiB -5e;8 MiB;7;94 MiB;9 MiB -6e;8 MiB;8;94 MiB;9 MiB -7e;16 MiB;8;186 MiB;17 MiB -8e;32 MiB;8;370 MiB;33 MiB -9e;64 MiB;8;674 MiB;65 MiB For example, there are a total of four presets that use 8 MiB dictionary, whose order from the fastest to the slowest is -5, -6, -5e, and -6e. --fast --best These are somewhat misleading aliases for -0 and -9, respec‐ tively. These are provided only for backwards compatibility with LZMA Utils. Avoid using these options. --block-size=size When compressing to the .xz format, split the input data into blocks of size bytes. The blocks are compressed independently from each other, which helps with multi-threading and makes lim‐ ited random-access decompression possible. This option is typi‐ cally used to override the default block size in multi-threaded mode, but this option can be used in single-threaded mode too. In multi-threaded mode about three times size bytes will be al‐ located in each thread for buffering input and output. The de‐ fault size is three times the LZMA2 dictionary size or 1 MiB, whichever is more. Typically a good value is 2–4 times the size of the LZMA2 dictionary or at least 1 MiB. Using size less than the LZMA2 dictionary size is waste of RAM because then the LZMA2 dictionary buffer will never get fully used. In multi-threaded mode, the sizes of the blocks are stored in the block headers. This size information is required for multi-threaded decompres‐ sion. In single-threaded mode no block splitting is done by default. Setting this option doesn't affect memory usage. No size infor‐ mation is stored in block headers, thus files created in single- threaded mode won't be identical to files created in multi- threaded mode. The lack of size information also means that xz won't be able decompress the files in multi-threaded mode. --block-list=items When compressing to the .xz format, start a new block with an optional custom filter chain after the given intervals of uncom‐ pressed data. The items are a comma-separated list. Each item consists of an optional filter chain number between 0 and 9 followed by a colon (:) and a required size of uncompressed data. Omitting an item (two or more consecutive commas) is a shorthand to use the size and filters of the previous item. If the input file is bigger than the sum of the sizes in items, the last item is repeated until the end of the file. A special value of 0 may be used as the last size to indicate that the rest of the file should be encoded as a single block. An alternative filter chain for each block can be specified in combination with the --filters1=filters ... --filters9=filters options. These options define filter chains with an identifier between 1–9. Filter chain 0 can be used to refer to the default filter chain, which is the same as not specifying a filter chain. The filter chain identifier can be used before the un‐ compressed size, followed by a colon (:). For example, if one specifies --block-list=1:2MiB,3:2MiB,2:4MiB,,2MiB,0:4MiB then blocks will be created using: • The filter chain specified by --filters1 and 2 MiB input • The filter chain specified by --filters3 and 2 MiB input • The filter chain specified by --filters2 and 4 MiB input • The filter chain specified by --filters2 and 4 MiB input • The default filter chain and 2 MiB input • The default filter chain and 4 MiB input for every block un‐ til end of input. If one specifies a size that exceeds the encoder's block size (either the default value in threaded mode or the value speci‐ fied with --block-size=size), the encoder will create additional blocks while keeping the boundaries specified in items. For ex‐ ample, if one specifies --block-size=10MiB --block-list=5MiB,10MiB,8MiB,12MiB,24MiB and the input file is 80 MiB, one will get 11 blocks: 5, 10, 8, 10, 2, 10, 10, 4, 10, 10, and 1 MiB. In multi-threaded mode the sizes of the blocks are stored in the block headers. This isn't done in single-threaded mode, so the encoded output won't be identical to that of the multi-threaded mode. --flush-timeout=timeout When compressing, if more than timeout milliseconds (a positive integer) has passed since the previous flush and reading more input would block, all the pending input data is flushed from the encoder and made available in the output stream. This can be useful if xz is used to compress data that is streamed over a network. Small timeout values make the data available at the receiving end with a small delay, but large timeout values give better compression ratio. This feature is disabled by default. If this option is speci‐ fied more than once, the last one takes effect. The special timeout value of 0 can be used to explicitly disable this fea‐ ture. This feature is not available on non-POSIX systems. This feature is still experimental. Currently xz is unsuitable for decompressing the stream in real time due to how xz does buffering. --memlimit-compress=limit Set a memory usage limit for compression. If this option is specified multiple times, the last one takes effect. If the compression settings exceed the limit, xz will attempt to adjust the settings downwards so that the limit is no longer ex‐ ceeded and display a notice that automatic adjustment was done. The adjustments are done in this order: reducing the number of threads, switching to single-threaded mode if even one thread in multi-threaded mode exceeds the limit, and finally reducing the LZMA2 dictionary size. When compressing with --format=raw or if --no-adjust has been specified, only the number of threads may be reduced since it can be done without affecting the compressed output. If the limit cannot be met even with the adjustments described above, an error is displayed and xz will exit with exit status 1. The limit can be specified in multiple ways: • The limit can be an absolute value in bytes. Using an inte‐ ger suffix like MiB can be useful. Example: --memlimit-com‐ press=80MiB • The limit can be specified as a percentage of total physical memory (RAM). This can be useful especially when setting the XZ_DEFAULTS environment variable in a shell initialization script that is shared between different computers. That way the limit is automatically bigger on systems with more mem‐ ory. Example: --memlimit-compress=70% • The limit can be reset back to its default value by setting it to 0. This is currently equivalent to setting the limit to max (no memory usage limit). For 32-bit xz there is a special case: if the limit would be over 4020 MiB, the limit is set to 4020 MiB. On MIPS32 2000 MiB is used instead. (The values 0 and max aren't affected by this. A similar feature doesn't exist for decompression.) This can be helpful when a 32-bit executable has access to 4 GiB address space (2 GiB on MIPS32) while hopefully doing no harm in other situations. See also the section Memory usage. --memlimit-decompress=limit Set a memory usage limit for decompression. This also affects the --list mode. If the operation is not possible without ex‐ ceeding the limit, xz will display an error and decompressing the file will fail. See --memlimit-compress=limit for possible ways to specify the limit. --memlimit-mt-decompress=limit Set a memory usage limit for multi-threaded decompression. This can only affect the number of threads; this will never make xz refuse to decompress a file. If limit is too low to allow any multi-threading, the limit is ignored and xz will continue in single-threaded mode. Note that if also --memlimit-decompress is used, it will always apply to both single-threaded and multi- threaded modes, and so the effective limit for multi-threading will never be higher than the limit set with --memlimit-decom‐ press. In contrast to the other memory usage limit options, --mem‐ limit-mt-decompress=limit has a system-specific default limit. xz --info-memory can be used to see the current value. This option and its default value exist because without any limit the threaded decompressor could end up allocating an in‐ sane amount of memory with some input files. If the default limit is too low on your system, feel free to increase the limit but never set it to a value larger than the amount of usable RAM as with appropriate input files xz will attempt to use that amount of memory even with a low number of threads. Running out of memory or swapping will not improve decompression perfor‐ mance. See --memlimit-compress=limit for possible ways to specify the limit. Setting limit to 0 resets the limit to the default sys‐ tem-specific value. -M limit, --memlimit=limit, --memory=limit This is equivalent to specifying --memlimit-compress=limit --memlimit-decompress=limit --memlimit-mt-decompress=limit. --no-adjust Display an error and exit if the memory usage limit cannot be met without adjusting settings that affect the compressed out‐ put. That is, this prevents xz from switching the encoder from multi-threaded mode to single-threaded mode and from reducing the LZMA2 dictionary size. Even when this option is used the number of threads may be reduced to meet the memory usage limit as that won't affect the compressed output. Automatic adjusting is always disabled when creating raw streams (--format=raw). -T threads, --threads=threads Specify the number of worker threads to use. Setting threads to a special value 0 makes xz use up to as many threads as the pro‐ cessor(s) on the system support. The actual number of threads can be fewer than threads if the input file is not big enough for threading with the given settings or if using more threads would exceed the memory usage limit. The single-threaded and multi-threaded compressors produce dif‐ ferent output. Single-threaded compressor will give the small‐ est file size but only the output from the multi-threaded com‐ pressor can be decompressed using multiple threads. Setting threads to 1 will use the single-threaded mode. Setting threads to any other value, including 0, will use the multi-threaded compressor even if the system supports only one hardware thread. (xz 5.2.x used single-threaded mode in this situation.) To use multi-threaded mode with only one thread, set threads to +1. The + prefix has no effect with values other than 1. A memory usage limit can still make xz switch to single-threaded mode unless --no-adjust is used. Support for the + prefix was added in xz 5.4.0. If an automatic number of threads has been requested and no mem‐ ory usage limit has been specified, then a system-specific de‐ fault soft limit will be used to possibly limit the number of threads. It is a soft limit in sense that it is ignored if the number of threads becomes one, thus a soft limit will never stop xz from compressing or decompressing. This default soft limit will not make xz switch from multi-threaded mode to single- threaded mode. The active limits can be seen with xz --info-memory. Currently the only threading method is to split the input into blocks and compress them independently from each other. The de‐ fault block size depends on the compression level and can be overridden with the --block-size=size option. Threaded decompression only works on files that contain multiple blocks with size information in block headers. All large enough files compressed in multi-threaded mode meet this condition, but files compressed in single-threaded mode don't even if --block-size=size has been used. The default value for threads is 0. In xz 5.4.x and older the default is 1. Custom compressor filter chains A custom filter chain allows specifying the compression settings in de‐ tail instead of relying on the settings associated to the presets. When a custom filter chain is specified, preset options (-0 ... -9 and --extreme) earlier on the command line are forgotten. If a preset op‐ tion is specified after one or more custom filter chain options, the new preset takes effect and the custom filter chain options specified earlier are forgotten. A filter chain is comparable to piping on the command line. When com‐ pressing, the uncompressed input goes to the first filter, whose output goes to the next filter (if any). The output of the last filter gets written to the compressed file. The maximum number of filters in the chain is four, but typically a filter chain has only one or two fil‐ ters. Many filters have limitations on where they can be in the filter chain: some filters can work only as the last filter in the chain, some only as a non-last filter, and some work in any position in the chain. De‐ pending on the filter, this limitation is either inherent to the filter design or exists to prevent security issues. A custom filter chain can be specified in two different ways. The op‐ tions --filters=filters and --filters1=filters ... --filters9=filters allow specifying an entire filter chain in one option using the liblzma filter string syntax. Alternatively, a filter chain can be specified by using one or more individual filter options in the order they are wanted in the filter chain. That is, the order of the individual fil‐ ter options is significant! When decoding raw streams (--format=raw), the filter chain must be specified in the same order as it was speci‐ fied when compressing. Any individual filter or preset options speci‐ fied before the full chain option (--filters=filters) will be forgot‐ ten. Individual filters specified after the full chain option will re‐ set the filter chain. Both the full and individual filter options take filter-specific op‐ tions as a comma-separated list. Extra commas in options are ignored. Every option has a default value, so specify those you want to change. To see the whole filter chain and options, use xz -vv (that is, use --verbose twice). This works also for viewing the filter chain options used by presets. --filters=filters Specify the full filter chain or a preset in a single option. Each filter can be separated by spaces or two dashes (--). fil‐ ters may need to be quoted on the shell command line so it is parsed as a single option. To denote options, use : or =. A preset can be prefixed with a - and followed with zero or more flags. The only supported flag is e to apply the same options as --extreme. --filters1=filters ... --filters9=filters Specify up to nine additional filter chains that can be used with --block-list. For example, when compressing an archive with executable files followed by text files, the executable part could use a filter chain with a BCJ filter and the text part only the LZMA2 filter. --filters-help Display a help message describing how to specify presets and custom filter chains in the --filters and --filters1=filters ... --filters9=filters options, and exit successfully. --lzma1[=options] --lzma2[=options] Add LZMA1 or LZMA2 filter to the filter chain. These filters can be used only as the last filter in the chain. LZMA1 is a legacy filter, which is supported almost solely due to the legacy .lzma file format, which supports only LZMA1. LZMA2 is an updated version of LZMA1 to fix some practical is‐ sues of LZMA1. The .xz format uses LZMA2 and doesn't support LZMA1 at all. Compression speed and ratios of LZMA1 and LZMA2 are practically the same. LZMA1 and LZMA2 share the same set of options: preset=preset Reset all LZMA1 or LZMA2 options to preset. Preset con‐ sist of an integer, which may be followed by single-let‐ ter preset modifiers. The integer can be from 0 to 9, matching the command line options -0 ... -9. The only supported modifier is currently e, which matches --ex‐ treme. If no preset is specified, the default values of LZMA1 or LZMA2 options are taken from the preset 6. dict=size Dictionary (history buffer) size indicates how many bytes of the recently processed uncompressed data is kept in memory. The algorithm tries to find repeating byte se‐ quences (matches) in the uncompressed data, and replace them with references to the data currently in the dictio‐ nary. The bigger the dictionary, the higher is the chance to find a match. Thus, increasing dictionary size usually improves compression ratio, but a dictionary big‐ ger than the uncompressed file is waste of memory. Typical dictionary size is from 64 KiB to 64 MiB. The minimum is 4 KiB. The maximum for compression is cur‐ rently 1.5 GiB (1536 MiB). The decompressor already sup‐ ports dictionaries up to one byte less than 4 GiB, which is the maximum for the LZMA1 and LZMA2 stream formats. Dictionary size and match finder (mf) together determine the memory usage of the LZMA1 or LZMA2 encoder. The same (or bigger) dictionary size is required for decompressing that was used when compressing, thus the memory usage of the decoder is determined by the dictionary size used when compressing. The .xz headers store the dictionary size either as 2^n or 2^n + 2^(n-1), so these sizes are somewhat preferred for compression. Other sizes will get rounded up when stored in the .xz headers. lc=lc Specify the number of literal context bits. The minimum is 0 and the maximum is 4; the default is 3. In addi‐ tion, the sum of lc and lp must not exceed 4. All bytes that cannot be encoded as matches are encoded as literals. That is, literals are simply 8-bit bytes that are encoded one at a time. The literal coding makes an assumption that the highest lc bits of the previous uncompressed byte correlate with the next byte. For example, in typical English text, an upper-case letter is often followed by a lower-case let‐ ter, and a lower-case letter is usually followed by an‐ other lower-case letter. In the US-ASCII character set, the highest three bits are 010 for upper-case letters and 011 for lower-case letters. When lc is at least 3, the literal coding can take advantage of this property in the uncompressed data. The default value (3) is usually good. If you want maxi‐ mum compression, test lc=4. Sometimes it helps a little, and sometimes it makes compression worse. If it makes it worse, test lc=2 too. lp=lp Specify the number of literal position bits. The minimum is 0 and the maximum is 4; the default is 0. Lp affects what kind of alignment in the uncompressed data is assumed when encoding literals. See pb below for more information about alignment. pb=pb Specify the number of position bits. The minimum is 0 and the maximum is 4; the default is 2. Pb affects what kind of alignment in the uncompressed data is assumed in general. The default means four-byte alignment (2^pb=2^2=4), which is often a good choice when there's no better guess. When the alignment is known, setting pb accordingly may reduce the file size a little. For example, with text files having one-byte alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can improve compression slightly. For UTF-16 text, pb=1 is a good choice. If the alignment is an odd number like 3 bytes, pb=0 might be the best choice. Even though the assumed alignment can be adjusted with pb and lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment. It might be worth taking into account when designing file formats that are likely to be often com‐ pressed with LZMA1 or LZMA2. mf=mf Match finder has a major effect on encoder speed, memory usage, and compression ratio. Usually Hash Chain match finders are faster than Binary Tree match finders. The default depends on the preset: 0 uses hc3, 1–3 use hc4, and the rest use bt4. The following match finders are supported. The memory usage formulas below are rough approximations, which are closest to the reality when dict is a power of two. hc3 Hash Chain with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 7.5 (if dict <= 16 MiB); dict * 5.5 + 64 MiB (if dict > 16 MiB) hc4 Hash Chain with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 7.5 (if dict <= 32 MiB); dict * 6.5 (if dict > 32 MiB) bt2 Binary Tree with 2-byte hashing Minimum value for nice: 2 Memory usage: dict * 9.5 bt3 Binary Tree with 2- and 3-byte hashing Minimum value for nice: 3 Memory usage: dict * 11.5 (if dict <= 16 MiB); dict * 9.5 + 64 MiB (if dict > 16 MiB) bt4 Binary Tree with 2-, 3-, and 4-byte hashing Minimum value for nice: 4 Memory usage: dict * 11.5 (if dict <= 32 MiB); dict * 10.5 (if dict > 32 MiB) mode=mode Compression mode specifies the method to analyze the data produced by the match finder. Supported modes are fast and normal. The default is fast for presets 0–3 and nor‐ mal for presets 4–9. Usually fast is used with Hash Chain match finders and normal with Binary Tree match finders. This is also what the presets do. nice=nice Specify what is considered to be a nice length for a match. Once a match of at least nice bytes is found, the algorithm stops looking for possibly better matches. Nice can be 2–273 bytes. Higher values tend to give bet‐ ter compression ratio at the expense of speed. The de‐ fault depends on the preset. depth=depth Specify the maximum search depth in the match finder. The default is the special value of 0, which makes the compressor determine a reasonable depth from mf and nice. Reasonable depth for Hash Chains is 4–100 and 16–1000 for Binary Trees. Using very high values for depth can make the encoder extremely slow with some files. Avoid set‐ ting the depth over 1000 unless you are prepared to in‐ terrupt the compression in case it is taking far too long. When decoding raw streams (--format=raw), LZMA2 needs only the dictionary size. LZMA1 needs also lc, lp, and pb. --x86[=options] --arm[=options] --armthumb[=options] --arm64[=options] --powerpc[=options] --ia64[=options] --sparc[=options] --riscv[=options] Add a branch/call/jump (BCJ) filter to the filter chain. These filters can be used only as a non-last filter in the filter chain. A BCJ filter converts relative addresses in the machine code to their absolute counterparts. This doesn't change the size of the data but it increases redundancy, which can help LZMA2 to produce 0–15 % smaller .xz file. The BCJ filters are always re‐ versible, so using a BCJ filter for wrong type of data doesn't cause any data loss, although it may make the compression ratio slightly worse. The BCJ filters are very fast and use an in‐ significant amount of memory. These BCJ filters have known problems related to the compression ratio: • Some types of files containing executable code (for example, object files, static libraries, and Linux kernel modules) have the addresses in the instructions filled with filler values. These BCJ filters will still do the address conver‐ sion, which will make the compression worse with these files. • If a BCJ filter is applied on an archive, it is possible that it makes the compression ratio worse than not using a BCJ filter. For example, if there are similar or even identical executables then filtering will likely make the files less similar and thus compression is worse. The contents of non- executable files in the same archive can matter too. In practice one has to try with and without a BCJ filter to see which is better in each situation. Different instruction sets have different alignment: the exe‐ cutable file must be aligned to a multiple of this value in the input data to make the filter work. tab(;); l n l l n l. Filter;Alignment;Notes x86;1;32-bit or 64-bit x86 ARM;4; ARM-Thumb;2; ARM64;4;4096-byte alignment is best PowerPC;4;Big endian only IA-64;16;Ita‐ nium SPARC;4; RISC-V;2; Since the BCJ-filtered data is usually compressed with LZMA2, the compression ratio may be improved slightly if the LZMA2 op‐ tions are set to match the alignment of the selected BCJ filter. Examples: • IA-64 filter has 16-byte alignment so pb=4,lp=4,lc=0 is good with LZMA2 (2^4=16). • RISC-V code has 2-byte or 4-byte alignment depending on whether the file contains 16-bit compressed instructions (the C extension). When 16-bit instructions are used, pb=2,lp=1,lc=3 or pb=1,lp=1,lc=3 is good. When 16-bit in‐ structions aren't present, pb=2,lp=2,lc=2 is the best. read‐ elf -h can be used to check if "RVC" appears on the "Flags" line. • ARM64 is always 4-byte aligned so pb=2,lp=2,lc=2 is the best. • The x86 filter is an exception. It's usually good to stick to LZMA2's defaults (pb=2,lp=0,lc=3) when compressing x86 ex‐ ecutables. All BCJ filters support the same options: start=offset Specify the start offset that is used when converting be‐ tween relative and absolute addresses. The offset must be a multiple of the alignment of the filter (see the ta‐ ble above). The default is zero. In practice, the de‐ fault is good; specifying a custom offset is almost never useful. --delta[=options] Add the Delta filter to the filter chain. The Delta filter can be only used as a non-last filter in the filter chain. Currently only simple byte-wise delta calculation is supported. It can be useful when compressing, for example, uncompressed bitmap images or uncompressed PCM audio. However, special pur‐ pose algorithms may give significantly better results than Delta + LZMA2. This is true especially with audio, which compresses faster and better, for example, with flac(1). Supported options: dist=distance Specify the distance of the delta calculation in bytes. distance must be 1–256. The default is 1. For example, with dist=2 and eight-byte input A1 B1 A2 B3 A3 B5 A4 B7, the output will be A1 B1 01 02 01 02 01 02. Other options -q, --quiet Suppress warnings and notices. Specify this twice to suppress errors too. This option has no effect on the exit status. That is, even if a warning was suppressed, the exit status to indi‐ cate a warning is still used. -v, --verbose Be verbose. If standard error is connected to a terminal, xz will display a progress indicator. Specifying --verbose twice will give even more verbose output. The progress indicator shows the following information: • Completion percentage is shown if the size of the input file is known. That is, the percentage cannot be shown in pipes. • Amount of compressed data produced (compressing) or consumed (decompressing). • Amount of uncompressed data consumed (compressing) or pro‐ duced (decompressing). • Compression ratio, which is calculated by dividing the amount of compressed data processed so far by the amount of uncom‐ pressed data processed so far. • Compression or decompression speed. This is measured as the amount of uncompressed data consumed (compression) or pro‐ duced (decompression) per second. It is shown after a few seconds have passed since xz started processing the file. • Elapsed time in the format M:SS or H:MM:SS. • Estimated remaining time is shown only when the size of the input file is known and a couple of seconds have already passed since xz started processing the file. The time is shown in a less precise format which never has any colons, for example, 2 min 30 s. When standard error is not a terminal, --verbose will make xz print the filename, compressed size, uncompressed size, compres‐ sion ratio, and possibly also the speed and elapsed time on a single line to standard error after compressing or decompressing the file. The speed and elapsed time are included only when the operation took at least a few seconds. If the operation didn't finish, for example, due to user interruption, also the comple‐ tion percentage is printed if the size of the input file is known. -Q, --no-warn Don't set the exit status to 2 even if a condition worth a warn‐ ing was detected. This option doesn't affect the verbosity level, thus both --quiet and --no-warn have to be used to not display warnings and to not alter the exit status. --robot Print messages in a machine-parsable format. This is intended to ease writing frontends that want to use xz instead of li‐ blzma, which may be the case with various scripts. The output with this option enabled is meant to be stable across xz re‐ leases. See the section ROBOT MODE for details. --info-memory Display, in human-readable format, how much physical memory (RAM) and how many processor threads xz thinks the system has and the memory usage limits for compression and decompression, and exit successfully. -h, --help Display a help message describing the most commonly used op‐ tions, and exit successfully. -H, --long-help Display a help message describing all features of xz, and exit successfully -V, --version Display the version number of xz and liblzma in human readable format. To get machine-parsable output, specify --robot before --version. ROBOT MODE The robot mode is activated with the --robot option. It makes the out‐ put of xz easier to parse by other programs. Currently --robot is sup‐ ported only together with --list, --filters-help, --info-memory, and --version. It will be supported for compression and decompression in the future. List mode xz --robot --list uses tab-separated output. The first column of every line has a string that indicates the type of the information found on that line: name This is always the first line when starting to list a file. The second column on the line is the filename. file This line contains overall information about the .xz file. This line is always printed after the name line. stream This line type is used only when --verbose was specified. There are as many stream lines as there are streams in the .xz file. block This line type is used only when --verbose was specified. There are as many block lines as there are blocks in the .xz file. The block lines are shown after all the stream lines; different line types are not interleaved. summary This line type is used only when --verbose was specified twice. This line is printed after all block lines. Like the file line, the summary line contains overall information about the .xz file. totals This line is always the very last line of the list output. It shows the total counts and sizes. The columns of the file lines: 2. Number of streams in the file 3. Total number of blocks in the stream(s) 4. Compressed size of the file 5. Uncompressed size of the file 6. Compression ratio, for example, 0.123. If ratio is over 9.999, three dashes (---) are displayed instead of the ra‐ tio. 7. Comma-separated list of integrity check names. The follow‐ ing strings are used for the known check types: None, CRC32, CRC64, and SHA-256. For unknown check types, Unknown-N is used, where N is the Check ID as a decimal number (one or two digits). 8. Total size of stream padding in the file The columns of the stream lines: 2. Stream number (the first stream is 1) 3. Number of blocks in the stream 4. Compressed start offset 5. Uncompressed start offset 6. Compressed size (does not include stream padding) 7. Uncompressed size 8. Compression ratio 9. Name of the integrity check 10. Size of stream padding The columns of the block lines: 2. Number of the stream containing this block 3. Block number relative to the beginning of the stream (the first block is 1) 4. Block number relative to the beginning of the file 5. Compressed start offset relative to the beginning of the file 6. Uncompressed start offset relative to the beginning of the file 7. Total compressed size of the block (includes headers) 8. Uncompressed size 9. Compression ratio 10. Name of the integrity check If --verbose was specified twice, additional columns are included on the block lines. These are not displayed with a single --verbose, be‐ cause getting this information requires many seeks and can thus be slow: 11. Value of the integrity check in hexadecimal 12. Block header size 13. Block flags: c indicates that compressed size is present, and u indicates that uncompressed size is present. If the flag is not set, a dash (-) is shown instead to keep the string length fixed. New flags may be added to the end of the string in the future. 14. Size of the actual compressed data in the block (this ex‐ cludes the block header, block padding, and check fields) 15. Amount of memory (in bytes) required to decompress this block with this xz version 16. Filter chain. Note that most of the options used at com‐ pression time cannot be known, because only the options that are needed for decompression are stored in the .xz headers. The columns of the summary lines: 2. Amount of memory (in bytes) required to decompress this file with this xz version 3. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 4. Minimum xz version required to decompress the file The columns of the totals line: 2. Number of streams 3. Number of blocks 4. Compressed size 5. Uncompressed size 6. Average compression ratio 7. Comma-separated list of integrity check names that were present in the files 8. Stream padding size 9. Number of files. This is here to keep the order of the ear‐ lier columns the same as on file lines. If --verbose was specified twice, additional columns are included on the totals line: 10. Maximum amount of memory (in bytes) required to decompress the files with this xz version 11. yes or no indicating if all block headers have both com‐ pressed size and uncompressed size stored in them Since xz 5.1.2alpha: 12. Minimum xz version required to decompress the file Future versions may add new line types and new columns can be added to the existing line types, but the existing columns won't be changed. Filters help xz --robot --filters-help prints the supported filters in the following format: filter:option=<value>,option=<value>... filter Name of the filter option Name of a filter specific option value Numeric value ranges appear as <min-max>. String value choices are shown within < > and separated by a | character. Each filter is printed on its own line. Memory limit information xz --robot --info-memory prints a single line with multiple tab-sepa‐ rated columns: 1. Total amount of physical memory (RAM) in bytes. 2. Memory usage limit for compression in bytes (--memlimit-compress). A special value of 0 indicates the default setting which for sin‐ gle-threaded mode is the same as no limit. 3. Memory usage limit for decompression in bytes (--memlimit-decom‐ press). A special value of 0 indicates the default setting which for single-threaded mode is the same as no limit. 4. Since xz 5.3.4alpha: Memory usage for multi-threaded decompression in bytes (--memlimit-mt-decompress). This is never zero because a system-specific default value shown in the column 5 is used if no limit has been specified explicitly. This is also never greater than the value in the column 3 even if a larger value has been specified with --memlimit-mt-decompress. 5. Since xz 5.3.4alpha: A system-specific default memory usage limit that is used to limit the number of threads when compressing with an automatic number of threads (--threads=0) and no memory usage limit has been specified (--memlimit-compress). This is also used as the default value for --memlimit-mt-decompress. 6. Since xz 5.3.4alpha: Number of available processor threads. In the future, the output of xz --robot --info-memory may have more columns, but never more than a single line. Version xz --robot --version prints the version number of xz and liblzma in the following format: XZ_VERSION=XYYYZZZS LIBLZMA_VERSION=XYYYZZZS X Major version. YYY Minor version. Even numbers are stable. Odd numbers are alpha or beta versions. ZZZ Patch level for stable releases or just a counter for develop‐ ment releases. S Stability. 0 is alpha, 1 is beta, and 2 is stable. S should be always 2 when YYY is even. XYYYZZZS are the same on both lines if xz and liblzma are from the same XZ Utils release. Examples: 4.999.9beta is 49990091 and 5.0.0 is 50000002. EXIT STATUS 0 All is good. 1 An error occurred. 2 Something worth a warning occurred, but no actual errors oc‐ curred. Notices (not warnings or errors) printed on standard error don't affect the exit status. ENVIRONMENT xz parses space-separated lists of options from the environment vari‐ ables XZ_DEFAULTS and XZ_OPT, in this order, before parsing the options from the command line. Note that only options are parsed from the en‐ vironment variables; all non-options are silently ignored. Parsing is done with getopt_long(3) which is used also for the command line argu‐ ments. XZ_DEFAULTS User-specific or system-wide default options. Typically this is set in a shell initialization script to enable xz's memory usage limiter by default. Excluding shell initialization scripts and similar special cases, scripts must never set or unset XZ_DE‐ FAULTS. XZ_OPT This is for passing options to xz when it is not possible to set the options directly on the xz command line. This is the case when xz is run by a script or tool, for example, GNU tar(1): XZ_OPT=-2v tar caf foo.tar.xz foo Scripts may use XZ_OPT, for example, to set script-specific de‐ fault compression options. It is still recommended to allow users to override XZ_OPT if that is reasonable. For example, in sh(1) scripts one may use something like this: XZ_OPT=${XZ_OPT-"-7e"} export XZ_OPT LZMA UTILS COMPATIBILITY The command line syntax of xz is practically a superset of lzma, un‐ lzma, and lzcat as found from LZMA Utils 4.32.x. In most cases, it is possible to replace LZMA Utils with XZ Utils without breaking existing scripts. There are some incompatibilities though, which may sometimes cause problems. Compression preset levels The numbering of the compression level presets is not identical in xz and LZMA Utils. The most important difference is how dictionary sizes are mapped to different presets. Dictionary size is roughly equal to the decompressor memory usage. tab(;); c c c c n n. Level;xz;LZMA Utils -0;256 KiB;N/A -1;1 MiB;64 KiB -2;2 MiB;1 MiB -3;4 MiB;512 KiB -4;4 MiB;1 MiB -5;8 MiB;2 MiB -6;8 MiB;4 MiB -7;16 MiB;8 MiB -8;32 MiB;16 MiB -9;64 MiB;32 MiB The dictionary size differences affect the compressor memory usage too, but there are some other differences between LZMA Utils and XZ Utils, which make the difference even bigger: tab(;); c c c c n n. Level;xz;LZMA Utils 4.32.x -0;3 MiB;N/A -1;9 MiB;2 MiB -2;17 MiB;12 MiB -3;32 MiB;12 MiB -4;48 MiB;16 MiB -5;94 MiB;26 MiB -6;94 MiB;45 MiB -7;186 MiB;83 MiB -8;370 MiB;159 MiB -9;674 MiB;311 MiB The default preset level in LZMA Utils is -7 while in XZ Utils it is -6, so both use an 8 MiB dictionary by default. Streamed vs. non-streamed .lzma files The uncompressed size of the file can be stored in the .lzma header. LZMA Utils does that when compressing regular files. The alternative is to mark that uncompressed size is unknown and use end-of-payload marker to indicate where the decompressor should stop. LZMA Utils uses this method when uncompressed size isn't known, which is the case, for example, in pipes. xz supports decompressing .lzma files with or without end-of-payload marker, but all .lzma files created by xz will use end-of-payload marker and have uncompressed size marked as unknown in the .lzma header. This may be a problem in some uncommon situations. For exam‐ ple, a .lzma decompressor in an embedded device might work only with files that have known uncompressed size. If you hit this problem, you need to use LZMA Utils or LZMA SDK to create .lzma files with known un‐ compressed size. Unsupported .lzma files The .lzma format allows lc values up to 8, and lp values up to 4. LZMA Utils can decompress files with any lc and lp, but always creates files with lc=3 and lp=0. Creating files with other lc and lp is possible with xz and with LZMA SDK. The implementation of the LZMA1 filter in liblzma requires that the sum of lc and lp must not exceed 4. Thus, .lzma files, which exceed this limitation, cannot be decompressed with xz. LZMA Utils creates only .lzma files which have a dictionary size of 2^n (a power of 2) but accepts files with any dictionary size. liblzma ac‐ cepts only .lzma files which have a dictionary size of 2^n or 2^n + 2^(n-1). This is to decrease false positives when detecting .lzma files. These limitations shouldn't be a problem in practice, since practically all .lzma files have been compressed with settings that liblzma will accept. Trailing garbage When decompressing, LZMA Utils silently ignore everything after the first .lzma stream. In most situations, this is a bug. This also means that LZMA Utils don't support decompressing concatenated .lzma files. If there is data left after the first .lzma stream, xz considers the file to be corrupt unless --single-stream was used. This may break ob‐ scure scripts which have assumed that trailing garbage is ignored. NOTES Compressed output may vary The exact compressed output produced from the same uncompressed input file may vary between XZ Utils versions even if compression options are identical. This is because the encoder can be improved (faster or bet‐ ter compression) without affecting the file format. The output can vary even between different builds of the same XZ Utils version, if different build options are used. The above means that once --rsyncable has been implemented, the result‐ ing files won't necessarily be rsyncable unless both old and new files have been compressed with the same xz version. This problem can be fixed if a part of the encoder implementation is frozen to keep rsynca‐ ble output stable across xz versions. Embedded .xz decompressors Embedded .xz decompressor implementations like XZ Embedded don't neces‐ sarily support files created with integrity check types other than none and crc32. Since the default is --check=crc64, you must use --check=none or --check=crc32 when creating files for embedded systems. Outside embedded systems, all .xz format decompressors support all the check types, or at least are able to decompress the file without veri‐ fying the integrity check if the particular check is not supported. XZ Embedded supports BCJ filters, but only with the default start off‐ set. EXAMPLES Basics Compress the file foo into foo.xz using the default compression level (-6), and remove foo if compression is successful: xz foo Decompress bar.xz into bar and don't remove bar.xz even if decompres‐ sion is successful: xz -dk bar.xz Create baz.tar.xz with the preset -4e (-4 --extreme), which is slower than the default -6, but needs less memory for compression and decom‐ pression (48 MiB and 5 MiB, respectively): tar cf - baz | xz -4e > baz.tar.xz A mix of compressed and uncompressed files can be decompressed to stan‐ dard output with a single command: xz -dcf a.txt b.txt.xz c.txt d.txt.lzma > abcd.txt Parallel compression of many files On GNU and *BSD, find(1) and xargs(1) can be used to parallelize com‐ pression of many files: find . -type f \! -name '*.xz' -print0 \ | xargs -0r -P4 -n16 xz -T1 The -P option to xargs(1) sets the number of parallel xz processes. The best value for the -n option depends on how many files there are to be compressed. If there are only a couple of files, the value should probably be 1; with tens of thousands of files, 100 or even more may be appropriate to reduce the number of xz processes that xargs(1) will eventually create. The option -T1 for xz is there to force it to single-threaded mode, be‐ cause xargs(1) is used to control the amount of parallelization. Robot mode Calculate how many bytes have been saved in total after compressing multiple files: xz --robot --list *.xz | awk '/^totals/{print $5-$4}' A script may want to know that it is using new enough xz. The follow‐ ing sh(1) script checks that the version number of the xz tool is at least 5.0.0. This method is compatible with old beta versions, which didn't support the --robot option: if ! eval "$(xz --robot --version 2> /dev/null)" || [ "$XZ_VERSION" -lt 50000002 ]; then echo "Your xz is too old." fi unset XZ_VERSION LIBLZMA_VERSION Set a memory usage limit for decompression using XZ_OPT, but if a limit has already been set, don't increase it: NEWLIM=$((123 << 20)) # 123 MiB OLDLIM=$(xz --robot --info-memory | cut -f3) if [ $OLDLIM -eq 0 -o $OLDLIM -gt $NEWLIM ]; then XZ_OPT="$XZ_OPT --memlimit-decompress=$NEWLIM" export XZ_OPT fi Custom compressor filter chains The simplest use for custom filter chains is customizing a LZMA2 pre‐ set. This can be useful, because the presets cover only a subset of the potentially useful combinations of compression settings. The CompCPU columns of the tables from the descriptions of the options -0 ... -9 and --extreme are useful when customizing LZMA2 presets. Here are the relevant parts collected from those two tables: tab(;); c c n n. Preset;CompCPU -0;0 -1;1 -2;2 -3;3 -4;4 -5;5 -6;6 -5e;7 -6e;8 If you know that a file requires somewhat big dictionary (for example, 32 MiB) to compress well, but you want to compress it quicker than xz -8 would do, a preset with a low CompCPU value (for example, 1) can be modified to use a bigger dictionary: xz --lzma2=preset=1,dict=32MiB foo.tar With certain files, the above command may be faster than xz -6 while compressing significantly better. However, it must be emphasized that only some files benefit from a big dictionary while keeping the CompCPU value low. The most obvious situation, where a big dictionary can help a lot, is an archive containing very similar files of at least a few megabytes each. The dictionary size has to be significantly bigger than any individual file to allow LZMA2 to take full advantage of the similarities between consecutive files. If very high compressor and decompressor memory usage is fine, and the file being compressed is at least several hundred megabytes, it may be useful to use an even bigger dictionary than the 64 MiB that xz -9 would use: xz -vv --lzma2=dict=192MiB big_foo.tar Using -vv (--verbose --verbose) like in the above example can be useful to see the memory requirements of the compressor and decompressor. Re‐ member that using a dictionary bigger than the size of the uncompressed file is waste of memory, so the above command isn't useful for small files. Sometimes the compression time doesn't matter, but the decompressor memory usage has to be kept low, for example, to make it possible to decompress the file on an embedded system. The following command uses -6e (-6 --extreme) as a base and sets the dictionary to only 64 KiB. The resulting file can be decompressed with XZ Embedded (that's why there is --check=crc32) using about 100 KiB of memory. xz --check=crc32 --lzma2=preset=6e,dict=64KiB foo If you want to squeeze out as many bytes as possible, adjusting the number of literal context bits (lc) and number of position bits (pb) can sometimes help. Adjusting the number of literal position bits (lp) might help too, but usually lc and pb are more important. For example, a source code archive contains mostly US-ASCII text, so something like the following might give slightly (like 0.1 %) smaller file than xz -6e (try also without lc=4): xz --lzma2=preset=6e,pb=0,lc=4 source_code.tar Using another filter together with LZMA2 can improve compression with certain file types. For example, to compress a x86-32 or x86-64 shared library using the x86 BCJ filter: xz --x86 --lzma2 libfoo.so Note that the order of the filter options is significant. If --x86 is specified after --lzma2, xz will give an error, because there cannot be any filter after LZMA2, and also because the x86 BCJ filter cannot be used as the last filter in the chain. The Delta filter together with LZMA2 can give good results with bitmap images. It should usually beat PNG, which has a few more advanced fil‐ ters than simple delta but uses Deflate for the actual compression. The image has to be saved in uncompressed format, for example, as un‐ compressed TIFF. The distance parameter of the Delta filter is set to match the number of bytes per pixel in the image. For example, 24-bit RGB bitmap needs dist=3, and it is also good to pass pb=0 to LZMA2 to accommodate the three-byte alignment: xz --delta=dist=3 --lzma2=pb=0 foo.tiff If multiple images have been put into a single archive (for example, .tar), the Delta filter will work on that too as long as all images have the same number of bytes per pixel. SEE ALSO xzdec(1), xzdiff(1), xzgrep(1), xzless(1), xzmore(1), gzip(1), bzip2(1), 7z(1) XZ Utils: <https://tukaani.org/xz/> XZ Embedded: <https://tukaani.org/xz/embedded.html> LZMA SDK: <https://7-zip.org/sdk.html> Tukaani 2024-12-30 XZ(1)