#Bash 的 tar 命令
tar [OPTION...] [FILE]...
tar -c [-f ARCHIVE] [OPTION...] [FILE...]
tar -x [-f ARCHIVE] [OPTION...] [MEMBER...]
tar -t [-f ARCHIVE] [OPTION...] [MEMBER...]
功能
将多个文件打包成单个归档文件,或查看、提取、更新归档文件中的内容;可与 gzip、bzip2、xz、zstd 等压缩程序配合,实现归档文件的压缩和解压。
tar(tape archiver)最初用于将文件备份到磁带,现在常用于打包和分发源代码、备份数据以及创建压缩包。
类型
可执行文件(/usr/bin/tar),属于 tar 软件包。
参数
OPTION选项:- 操作模式(必须且只能指定一个):
-A,--catenate,--concatenate- 将一个或多个归档文件追加到另一个归档文件的末尾;不能用于压缩归档-c,--create- 创建新的归档文件-d,--diff,--compare- 比较归档文件与文件系统中的对应文件--delete- 从归档文件中删除指定成员;不能用于压缩归档-r,--append- 将文件追加到归档文件末尾-t,--list- 列出归档文件的内容--test-label- 测试归档文件的卷标-u,--update- 仅追加比归档中对应副本更新的文件-x,--extract,--get- 从归档文件中提取文件--show-defaults- 显示内置默认值-?,--help- 显示帮助--usage- 显示可用选项列表--version- 显示版本
- 文件选择:
-f,--file=ARCHIVE- 指定归档文件或设备;-表示标准输入/输出。省略时依次使用环境变量TAPE和编译时的默认值-T,--files-from=FILE- 从FILE读取要处理的文件或成员名称,每行一个--null- 与-T配合,使用空字符(\0)分隔名称,适合处理find -print0的输出--verbatim-files-from- 将-T文件中的每一行都视为文件名,即使以-开头--no-verbatim-files-from- 恢复默认行为,以-开头的名称按选项处理-X,--exclude-from=FILE- 从FILE读取排除模式,每行一个--exclude=PATTERN- 排除匹配PATTERN的文件--exclude-backups- 排除备份文件和锁文件--exclude-vcs- 排除版本控制系统的目录(如.git、.svn)--exclude-vcs-ignores- 根据.gitignore、.cvsignore、.bzrignore、.hgignore等文件排除--exclude-caches- 排除包含CACHEDIR.TAG的目录内容,但保留标签文件--exclude-caches-all- 排除包含CACHEDIR.TAG的目录及其标签文件--exclude-caches-under- 排除包含CACHEDIR.TAG的目录中的所有内容--exclude-tag=FILE- 排除包含FILE的目录内容,但保留FILE--exclude-tag-all=FILE- 排除包含FILE的目录--exclude-tag-under=FILE- 排除包含FILE的目录中的所有内容--no-recursion- 不自动递归目录--recursion- 递归目录;默认-P,--absolute-names- 保留文件名开头的/,不删除绝对路径--strip-components=NUMBER- 提取时去掉文件名前NUMBER层路径--transform=EXPRESSION,--xform=EXPRESSION- 使用 sed 替换表达式转换文件名--show-transformed-names,--show-stored-names- 显示转换后的文件名--one-top-level[=DIR]- 将所有文件提取到DIR;省略参数时使用归档文件名(去掉压缩后缀)作为目录--add-file=FILE- 将FILE添加到归档,适用于以-开头的文件名-K,--starting-file=MEMBER- 从归档中的指定成员开始处理-N,--newer=DATE,--after-date=DATE- 仅处理比DATE新的文件--newer-mtime=DATE- 仅处理数据修改时间比DATE新的文件-h,--dereference- 跟随符号链接,归档其指向的文件--hard-dereference- 跟随硬链接,归档其指向的文件--one-file-system- 创建归档时停留在本地文件系统,不跨越挂载点
- 文件名匹配(同时影响排除和包含模式):
--anchored- 模式从文件名开头匹配--no-anchored- 模式在任意/之后匹配;排除模式默认--ignore-case- 忽略大小写--no-ignore-case- 区分大小写;默认--wildcards- 使用通配符;排除模式默认--no-wildcards- 按字面字符串匹配--wildcards-match-slash- 通配符可以匹配/;排除模式默认--no-wildcards-match-slash- 通配符不匹配/
- 覆盖控制:
-k,--keep-old-files- 提取时不覆盖已存在的文件,并报错--skip-old-files- 提取时不覆盖已存在的文件,静默跳过--keep-newer-files- 不覆盖比归档副本更新的文件--keep-directory-symlink- 提取时不替换指向目录的现有符号链接--overwrite- 提取时覆盖已存在的文件--overwrite-dir- 提取时覆盖已存在目录的元数据;默认--no-overwrite-dir- 保留已存在目录的元数据-U,--unlink-first- 提取前先删除同名文件--recursive-unlink- 提取目录前递归删除目录中的所有文件--remove-files- 将文件加入归档后从磁盘删除
- 文件属性:
-p,--preserve-permissions,--same-permissions- 提取时恢复归档中记录的权限;root 默认--same-owner- 提取时恢复归档中记录的所有者;root 默认--no-same-owner- 以当前用户身份提取;普通用户默认-m,--touch- 不恢复文件的修改时间--numeric-owner- 始终使用数字 UID/GID--owner=NAME[:UID]- 强制将新增文件的所有者设为NAME--owner-map=FILE- 从FILE读取所有者映射--group=NAME[:GID]- 强制将新增文件的所属组设为NAME--group-map=FILE- 从FILE读取所属组映射--mode=CHANGES- 强制将新增文件的权限设为CHANGES--mtime=DATE-OR-FILE- 设置新增文件的修改时间--clamp-mtime- 仅当文件时间晚于--mtime指定值时修改--atime-preserve[=METHOD]- 保留被归档文件的访问时间--delay-directory-restore- 提取结束前不设置目录的修改时间和权限--no-delay-directory-restore- 取消上一个选项的效果--sort=ORDER- 创建归档时按none、name或inode排序--acls/--no-acls- 启用/禁用 POSIX ACL 支持--selinux/--no-selinux- 启用/禁用 SELinux 上下文支持--xattrs/--no-xattrs- 启用/禁用扩展属性支持--xattrs-include=PATTERN- 指定要包含的扩展属性键模式--xattrs-exclude=PATTERN- 指定要排除的扩展属性键模式
- 压缩:
-a,--auto-compress- 根据归档文件后缀自动选择压缩程序--no-auto-compress- 不根据后缀选择压缩程序-z,--gzip,--gunzip,--ungzip- 使用 gzip 压缩/解压-j,--bzip2- 使用 bzip2 压缩/解压-J,--xz- 使用 xz 压缩/解压--zstd- 使用 zstd 压缩/解压-Z,--compress,--uncompress- 使用 compress 压缩/解压--lzip- 使用 lzip 压缩/解压--lzma- 使用 lzma 压缩/解压--lzop- 使用 lzop 压缩/解压-I,--use-compress-program=COMMAND- 使用指定的外部程序进行压缩/解压
- 归档格式:
-H,--format=FORMAT- 指定归档格式:gnu、oldgnu、posix(pax)、ustar、v7--old-archive,--portability- 等价于--format=v7--posix- 等价于--format=posix--pax-option=KEYWORD[[:]=VALUE]...- 创建 PAX 归档时控制 pax 关键字-V,--label=TEXT- 创建带卷标TEXT的归档;列出/提取时按卷标匹配
- 增量备份与稀疏文件:
-g,--listed-incremental=FILE- 创建新 GNU 格式增量备份,FILE为快照文件-G,--incremental- 创建旧 GNU 格式增量备份--level=NUMBER- 设置增量备份级别;目前仅0有意义--check-device- 创建增量备份时检查设备号;默认--no-check-device- 创建增量备份时不检查设备号-S,--sparse- 高效处理稀疏文件--hole-detection=METHOD- 设置稀疏文件的空洞检测方法:seek或raw--sparse-version=MAJOR[.MINOR]- 设置稀疏文件格式版本:0.0、0.1或1.0
- 多卷与设备:
-M,--multi-volume- 创建/列出/提取多卷归档-L,--tape-length=N- 写入N×1024字节后切换卷;隐含-M-F,--info-script=COMMAND,--new-volume-script=COMMAND- 每卷结束时运行命令;隐含-M--volno-file=FILE- 在FILE中记录多卷归档的当前卷号--force-local- 即使归档名包含冒号也视为本地文件--rmt-command=COMMAND- 指定远程访问时使用的rmt命令--rsh-command=COMMAND- 指定远程访问时使用的rsh命令(通常设为ssh)-b,--blocking-factor=BLOCKS- 将记录大小设为BLOCKS×512字节-B,--read-full-records- 读取不完整的输入记录-i,--ignore-zeros- 忽略归档中的全零块--record-size=NUMBER- 设置记录大小(字节,必须是 512 的倍数)-n,--seek- 假定归档可随机访问--no-seek- 假定归档不可随机访问
- 信息输出:
-v,--verbose- 详细列出处理的文件;可重复使用以提高详细程度,最多 3 级--totals[=SIGNAL]- 处理结束后输出总字节数--checkpoint[=N]- 每处理N个记录显示一次进度;默认 10--checkpoint-action=ACTION- 在每个检查点执行动作--index-file=FILE- 将详细输出写入FILE-R,--block-number- 在每条消息中显示归档内的块号--show-omitted-dirs- 列出不匹配搜索条件的目录--full-time- 以完整精度显示文件时间--utc- 以 UTC 显示文件修改时间-l,--check-links- 并非所有硬链接都被归档时输出消息--quoting-style=STYLE- 设置文件名引用风格--quote-chars=STRING- 额外引用STRING中的字符--no-quote-chars=STRING- 不引用STRING中的字符--warning=KEYWORD- 启用或禁用指定警告;以no-开头表示禁用
- 其它:
-C,--directory=DIR- 在执行操作前切换到目录DIR;对后面的选项和参数生效--occurrence[=N]- 仅处理每个文件在归档中的第N次出现--restrict- 禁用部分可能有害的选项--ignore-failed-read- 读取失败时不以非零状态退出--backup[=CONTROL]- 删除/覆盖前备份文件--suffix=STRING- 指定备份文件后缀;默认~-w,--interactive,--confirmation- 对每个操作进行确认-o- 创建时等价于--old-archive,提取时等价于--no-same-owner
- 操作模式(必须且只能指定一个):
FILE- 要归档或比较的文件或目录;具体含义取决于操作模式MEMBER- 归档文件中的成员(文件或目录)名称;具体含义取决于操作模式
tar支持传统、短选项和长选项三种风格。例如tar cfv demo.tar demo、tar -cvf demo.tar demo和tar --create --file=demo.tar --verbose demo是等价的。推荐使用短选项风格。
#示例
创建归档
$ tree demo
demo
├── a.txt
└── sub
└── b.txt
$ tar -cvf demo.tar demo # 将 demo 目录打包为 demo.tar
demo/
demo/a.txt
demo/sub/
demo/sub/b.txt
查看归档内容
$ tar -tf demo.tar # 仅列出成员名称
demo/
demo/a.txt
demo/sub/
demo/sub/b.txt
$ tar -tvf demo.tar # 显示权限、所有者、大小和时间
drwxr-xr-x user/user 0 2026-10-21 14:58 demo/
-rw-r--r-- user/user 6 2026-10-21 14:58 demo/a.txt
drwxr-xr-x user/user 0 2026-10-21 14:58 demo/sub/
-rw-r--r-- user/user 6 2026-10-21 14:58 demo/sub/b.txt
解压归档
$ mkdir out
$ tar -xvf demo.tar -C out # 解压到 out 目录,并显示过程
demo/
demo/a.txt
demo/sub/
demo/sub/b.txt
$ tree out
out
└── demo
├── a.txt
└── sub
└── b.txt
只提取指定文件
$ tar -xf demo.tar -C out demo/a.txt # 只提取 demo/a.txt
$ tar -xOf demo.tar demo/a.txt # 将文件内容提取到标准输出
hello
压缩归档
$ tar -czf demo.tar.gz demo # gzip
$ tar -cjf demo.tar.bz2 demo # bzip2
$ tar -cJf demo.tar.xz demo # xz
$ tar --zstd -cf demo.tar.zst demo # zstd
$ tar -caf demo.tar.gz demo # 根据后缀自动选择压缩程序
$ ls demo.tar*
demo.tar demo.tar.bz2 demo.tar.gz demo.tar.xz demo.tar.zst
使用
-j、-J、--zstd等选项时,需要系统已安装对应的压缩程序。
解压压缩归档
$ tar -xzf demo.tar.gz -C out # gzip
$ tar -xjf demo.tar.bz2 -C out # bzip2
$ tar -xJf demo.tar.xz -C out # xz
$ tar --zstd -xf demo.tar.zst -C out # zstd
$ tar -xaf demo.tar.gz -C out # 自动识别压缩格式
查看压缩归档内容
$ tar -tzf demo.tar.gz
demo/
demo/a.txt
demo/sub/
demo/sub/b.txt
排除文件
$ tar -czf project.tar.gz --exclude='*.log' --exclude='node_modules' project
--exclude的模式默认不锚定,可以匹配路径的任意部分- 需要从文件读取排除模式时,使用
-X, --exclude-from=FILE
从文件列表创建归档
$ find demo -type f > files.txt
$ tar -czf demo.tar.gz -T files.txt # 从 files.txt 读取要归档的文件
-T读取的名称默认按命令行参数处理,以-开头的名称会被当作选项- 文件名可能以
-开头时,使用--verbatim-files-from
追加与更新
$ tar -rvf demo.tar new.txt # 将 new.txt 追加到归档末尾
$ tar -uvf demo.tar demo # 仅追加比归档中副本更新的文件
-r和-u不能用于压缩归档。
比较归档与文件
$ tar -df demo.tar demo # 无输出表示归档与文件系统内容一致
$ echo $?
0
增量备份
$ tar -czf backup-0.tar.gz -g backup.snar demo # 0 级(完整)备份
$ echo 'new content' >> demo/a.txt # 修改文件
$ tar -czf backup-1.tar.gz -g backup.snar demo # 1 级(增量)备份
$ mkdir restore
$ tar -xzf backup-0.tar.gz -C restore -g /dev/null
$ tar -xzf backup-1.tar.gz -C restore -g /dev/null
backup.snar是快照文件,用于记录上次备份的状态- 增量归档中仍会包含目录项,以及自上次备份以来发生变化的文件
- 提取增量归档时需要按顺序提取,并用
-g /dev/null满足语法要求
保留权限和所有者
$ sudo tar -xpvf demo.tar -C /restore # 保留归档中记录的权限
$ sudo tar --same-owner -xvf demo.tar -C /restore # 保留归档中记录的所有者
- 普通用户提取时默认使用当前用户身份,只有 root 才会默认保留所有者
去掉路径前缀
$ mkdir out2
$ tar -xf demo.tar --strip-components=1 -C out2
$ tree out2
out2
├── a.txt
└── sub
└── b.txt
通过管道传输
$ tar -czf - demo | ssh user@host 'cat > demo.tar.gz' # 将归档写到标准输出并通过 SSH 传输
$ ssh user@host 'tar -czf - demo' | tar -xzf - # 从远程读取归档并解压到当前目录
#相关命令
#推荐阅读
#手册
TAR(1) GNU TAR Manual TAR(1)
NAME
tar - an archiving utility
SYNOPSIS
Traditional usage
tar {A|c|d|r|t|u|x}[GnSkUWOmpsMBiajJzZhPlRvwo] [ARG...]
UNIX-style usage
tar -A [OPTIONS] -f ARCHIVE ARCHIVE...
tar -c [-f ARCHIVE] [OPTIONS] [FILE...]
tar -d [-f ARCHIVE] [OPTIONS] [FILE...]
tar -r [-f ARCHIVE] [OPTIONS] [FILE...]
tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...]
tar -u [-f ARCHIVE] [OPTIONS] [FILE...]
tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...]
GNU-style usage
tar {--catenate|--concatenate} [OPTIONS] --file ARCHIVE ARCHIVE...
tar --create [--file ARCHIVE] [OPTIONS] [FILE...]
tar {--diff|--compare} [--file ARCHIVE] [OPTIONS] [FILE...]
tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...]
tar --append [--file ARCHIVE] [OPTIONS] [FILE...]
tar --list [--file ARCHIVE] [OPTIONS] [MEMBER...]
tar --test-label [--file ARCHIVE] [OPTIONS] [LABEL...]
tar --update [--file ARCHIVE] [OPTIONS] [FILE...]
tar {--extract|--get} [--file ARCHIVE] [OPTIONS] [MEMBER...]
NOTE
This manpage is a short description of GNU tar. For a detailed discus‐
sion, including examples and usage recommendations, refer to the GNU Tar
Manual available in texinfo format. If the info reader and the tar doc‐
umentation are properly installed on your system, the command
info tar
should give you access to the complete manual.
You can also view the manual using the info mode in emacs(1), or find it
in various formats online at
https://www.gnu.org/software/tar/manual
If any discrepancies occur between this manpage and the GNU Tar Manual,
the later shall be considered the authoritative source.
DESCRIPTION
GNU tar is an archiving program designed to store multiple files in a
single file (an archive), and to manipulate such archives. The archive
can be either a regular file or a device (e.g. a tape drive, hence the
name of the program, which stands for tape archiver), which can be lo‐
cated either on the local or on a remote machine.
Option styles
Options to GNU tar can be given in three different styles. In tradi‐
tional style, the first argument is a cluster of option letters and all
subsequent arguments supply arguments to those options that require
them. The arguments are read in the same order as the option letters.
Any command line words that remain after all options have been processed
are treated as non-option arguments: file or archive member names.
For example, the c option requires creating the archive, the v option
requests the verbose operation, and the f option takes an argument that
sets the name of the archive to operate upon. The following command,
written in the traditional style, instructs tar to store all files from
the directory /etc into the archive file etc.tar, verbosely listing the
files being archived:
tar cfv etc.tar /etc
In UNIX or short-option style, each option letter is prefixed with a
single dash, as in other command line utilities. If an option takes an
argument, the argument follows it, either as a separate command line
word, or immediately following the option. However, if the option takes
an optional argument, the argument must follow the option letter without
any intervening whitespace, as in -g/tmp/snar.db.
Any number of options not taking arguments can be clustered together af‐
ter a single dash, e.g. -vkp. An option that takes an argument (whether
mandatory or optional) can appear at the end of such a cluster, e.g.
-vkpf a.tar.
The example command above written in the short-option style could look
like:
tar -cvf etc.tar /etc
or
tar -c -v -f etc.tar /etc
In GNU or long-option style, each option begins with two dashes and has
a meaningful name, consisting of lower-case letters and dashes. When
used, the long option can be abbreviated to its initial letters, pro‐
vided that this does not create ambiguity. Arguments to long options
are supplied either as a separate command line word, immediately follow‐
ing the option, or separated from the option by an equals sign with no
intervening whitespace. Optional arguments must always use the latter
method.
Here are several ways of writing the example command in this style:
tar --create --file etc.tar --verbose /etc
or (abbreviating some options):
tar --cre --file=etc.tar --verb /etc
The options in all three styles can be intermixed, although doing so
with old options is not encouraged.
Operation mode
The options listed in the table below tell GNU tar what operation it is
to perform. Exactly one of them must be given. The meaning of non-op‐
tion arguments depends on the operation mode requested.
-A, --catenate, --concatenate
Append archives to the end of another archive. The arguments are
treated as the names of archives to append. All archives must be
of the same format as the archive they are appended to, otherwise
the resulting archive might be unusable with non-GNU implementa‐
tions of tar. Notice also that when more than one archive is
given, the members from archives other than the first one will be
accessible in the resulting archive only when using the -i (--ig‐
nore-zeros) option.
Compressed archives cannot be concatenated.
-c, --create
Create a new archive. Arguments supply the names of the files to
be archived. Directories are archived recursively, unless the
--no-recursion option is given.
-d, --diff, --compare
Find differences between archive and file system. The arguments
are optional and specify archive members to compare. If not
given, the current working directory is assumed.
--delete
Delete from the archive. The arguments supply names of the
archive members to be removed. At least one argument must be
given.
This option does not operate on compressed archives. There is no
short option equivalent.
-r, --append
Append files to the end of an archive. Arguments have the same
meaning as for -c (--create).
-t, --list
List the contents of an archive. Arguments are optional. When
given, they specify the names of the members to list.
--test-label
Test the archive volume label and exit. When used without argu‐
ments, it prints the volume label (if any) and exits with status
0. When one or more command line arguments are given. tar com‐
pares the volume label with each argument. It exits with code 0
if a match is found, and with code 1 otherwise. No output is
displayed, unless used together with the -v (--verbose) option.
There is no short option equivalent for this option.
-u, --update
Append files which are newer than the corresponding copy in the
archive. Arguments have the same meaning as with the -c and -r
options. Notice, that newer files don't replace their old
archive copies, but instead are appended to the end of archive.
The resulting archive can thus contain several members of the
same name, corresponding to various versions of the same file.
-x, --extract, --get
Extract files from an archive. Arguments are optional. When
given, they specify names of the archive members to be extracted.
--show-defaults
Show built-in defaults for various tar options and exit.
-?, --help
Display a short option summary and exit.
--usage
Display a list of available options and exit.
--version
Print program version and copyright information and exit.
OPTIONS
Operation modifiers
--check-device
Check device numbers when creating incremental archives (de‐
fault).
-g, --listed-incremental=FILE
Handle new GNU-format incremental backups. FILE is the name of a
snapshot file, where tar stores additional information which is
used to decide which files changed since the previous incremental
dump and, consequently, must be dumped again. If FILE does not
exist when creating an archive, it will be created and all files
will be added to the resulting archive (the level 0 dump). To
create incremental archives of non-zero level N, you need a copy
of the snapshot file created for level N-1, and use it as FILE.
When listing or extracting, the actual content of FILE is not in‐
spected, it is needed only due to syntactical requirements. It
is therefore common practice to use /dev/null in its place.
--hole-detection=METHOD
Use METHOD to detect holes in sparse files. This option implies
--sparse. Valid values for METHOD are seek and raw. Default is
seek with fallback to raw when not applicable.
-G, --incremental
Handle old GNU-format incremental backups.
--ignore-failed-read
Do not exit with nonzero on unreadable files.
--level=NUMBER
Set dump level for a created listed-incremental archive. Cur‐
rently only --level=0 is meaningful: it instructs tar to truncate
the snapshot file before dumping, thereby forcing a level 0 dump.
-n, --seek
Assume the archive is seekable. Normally tar determines automat‐
ically whether the archive can be seeked or not. This option is
intended for use in cases when such recognition fails. It takes
effect only if the archive is open for reading (e.g. with --list
or --extract options).
--no-check-device
Do not check device numbers when creating incremental archives.
--no-seek
Assume the archive is not seekable.
--occurrence[=N]
Process only the Nth occurrence of each file in the archive.
This option is valid only when used with one of the following
subcommands: --delete, --diff, --extract or --list and when a
list of files is given either on the command line or via the -T
option. The default N is 1.
--restrict
Disable the use of some potentially harmful options.
--sparse-version=MAJOR[.MINOR]
Set which version of the sparse format to use. This option im‐
plies --sparse. Valid argument values are 0.0, 0.1, and 1.0.
For a detailed discussion of sparse formats, refer to the GNU Tar
Manual, appendix D, "Sparse Formats". Using the info reader, it
can be accessed running the following command: info tar 'Sparse
Formats'.
-S, --sparse
Handle sparse files efficiently. Some files in the file system
may have segments which were actually never written (quite often
these are database files created by such systems as DBM). When
given this option, tar attempts to determine if the file is
sparse prior to archiving it, and if so, to reduce the resulting
archive size by not dumping empty parts of the file.
Overwrite control
These options control tar actions when extracting a file over an exist‐
ing copy on disk.
-k, --keep-old-files
Don't replace existing files when extracting.
--keep-newer-files
Don't replace existing files that are newer than their archive
copies.
--keep-directory-symlink
Don't replace existing symlinks to directories when extracting.
--no-overwrite-dir
Preserve metadata of existing directories.
--one-top-level[=DIR]
Extract all files into DIR, or, if used without argument, into a
subdirectory named by the base name of the archive (minus stan‐
dard compression suffixes recognizable by --auto-compress).
--overwrite
Overwrite existing files when extracting.
--overwrite-dir
Overwrite metadata of existing directories when extracting (de‐
fault).
--recursive-unlink
Recursively remove all files in the directory prior to extracting
it.
--remove-files
Remove files from disk after adding them to the archive.
--skip-old-files
Don't replace existing files when extracting, silently skip over
them.
-U, --unlink-first
Remove each file prior to extracting over it.
-W, --verify
Verify the archive after writing it.
Output stream selection
--ignore-command-error
Ignore subprocess exit codes.
--no-ignore-command-error
Treat non-zero exit codes of children as error (default).
-O, --to-stdout
Extract files to standard output.
--to-command=COMMAND
Pipe extracted files to COMMAND. The argument is the pathname of
an external program, optionally with command line arguments. The
program will be invoked and the contents of the file being ex‐
tracted supplied to it on its standard input. Additional data
will be supplied via the following environment variables:
TAR_FILETYPE
Type of the file. It is a single letter with the following
meaning:
f Regular file
d Directory
l Symbolic link
h Hard link
b Block device
c Character device
Currently only regular files are supported.
TAR_MODE
File mode, an octal number.
TAR_FILENAME
The name of the file.
TAR_REALNAME
Name of the file as stored in the archive.
TAR_UNAME
Name of the file owner.
TAR_GNAME
Name of the file owner group.
TAR_ATIME
Time of last access. It is a decimal number, representing
seconds since the Epoch. If the archive provides times
with nanosecond precision, the nanoseconds are appended to
the timestamp after a decimal point.
TAR_MTIME
Time of last modification.
TAR_CTIME
Time of last status change.
TAR_SIZE
Size of the file.
TAR_UID
UID of the file owner.
TAR_GID
GID of the file owner.
Additionally, the following variables contain information about
tar operation mode and the archive being processed:
TAR_VERSION
GNU tar version number.
TAR_ARCHIVE
The name of the archive tar is processing.
TAR_BLOCKING_FACTOR
Current blocking factor, i.e. number of 512-byte blocks in
a record.
TAR_VOLUME
Ordinal number of the volume tar is processing (set if
reading a multi-volume archive).
TAR_FORMAT
Format of the archive being processed. One of: gnu,
oldgnu, posix, ustar, v7.
TAR_SUBCOMMAND
A short option (with a leading dash) describing the opera‐
tion tar is executing.
Handling of file attributes
--atime-preserve[=METHOD]
Preserve access times on dumped files, either by restoring the
times after reading (METHOD=replace, this is the default) or by
not setting the times in the first place (METHOD=system).
--delay-directory-restore
Delay setting modification times and permissions of extracted di‐
rectories until the end of extraction. Use this option when ex‐
tracting from an archive which has unusual member ordering.
--group=NAME[:GID]
Force NAME as group for added files. If GID is not supplied,
NAME can be either a user name or numeric GID. In this case the
missing part (GID or name) will be inferred from the current
host's group database.
When used with --group-map=FILE, affects only those files whose
owner group is not listed in FILE.
--group-map=FILE
Read group translation map from FILE. Empty lines are ignored.
Comments are introduced with # sign and extend to the end of
line. Each non-empty line in FILE defines translation for a sin‐
gle group. It must consist of two fields, delimited by any
amount of whitespace:
OLDGRP NEWGRP[:NEWGID]
OLDGRP is either a valid group name or a GID prefixed with +.
Unless NEWGID is supplied, NEWGRP must also be either a valid
group name or a +GID. Otherwise, both NEWGRP and NEWGID need not
be listed in the system group database.
As a result, each input file with owner group OLDGRP will be
stored in archive with owner group NEWGRP and GID NEWGID.
--mode=CHANGES
Force symbolic mode CHANGES for added files.
--mtime=DATE-OR-FILE
Set mtime for added files. DATE-OR-FILE is either a date/time in
almost arbitrary format, or the name of an existing file. In the
latter case the mtime of that file will be used.
-m, --touch
Don't extract file modified time.
--no-delay-directory-restore
Cancel the effect of the prior --delay-directory-restore option.
--no-same-owner
Extract files as yourself (default for ordinary users).
--no-same-permissions
Apply the user's umask when extracting permissions from the
archive (default for ordinary users).
--numeric-owner
Always use numbers for user/group names.
--owner=NAME[:UID]
Force NAME as owner for added files. If UID is not supplied,
NAME can be either a user name or numeric UID. In this case the
missing part (UID or name) will be inferred from the current
host's user database.
When used with --owner-map=FILE, affects only those files whose
owner is not listed in FILE.
--owner-map=FILE
Read owner translation map from FILE. Empty lines are ignored.
Comments are introduced with # sign and extend to the end of
line. Each non-empty line in FILE defines translation for a sin‐
gle UID. It must consist of two fields, delimited by any amount
of whitespace:
OLDUSR NEWUSR[:NEWUID]
OLDUSR is either a valid user name or a UID prefixed with +. Un‐
less NEWUID is supplied, NEWUSR must also be either a valid user
name or a +UID. Otherwise, both NEWUSR and NEWUID need not be
listed in the system user database.
As a result, each input file owned by OLDUSR will be stored in
archive with owner name NEWUSR and UID NEWUID.
-p, --preserve-permissions, --same-permissions
Set permissions of extracted files to those recorded in the
archive (default for superuser).
--same-owner
Try extracting files with the same ownership as exists in the
archive (default for superuser).
-s, --preserve-order, --same-order
Tell tar that the list of file names to process is sorted in the
same order as the files in the archive.
--sort=ORDER
When creating an archive, sort directory entries according to OR‐
DER, which is one of none, name, or inode.
The default is --sort=none, which stores archive members in the
same order as returned by the operating system.
Using --sort=name ensures the member ordering in the created
archive is uniform and reproducible.
Using --sort=inode reduces the number of disk seeks made when
creating the archive and thus can considerably speed up archiva‐
tion. This sorting order is supported only if the underlying
system provides the necessary information.
Extended file attributes
--acls Enable POSIX ACLs support.
--no-acls
Disable POSIX ACLs support.
--selinux
Enable SELinux context support.
--no-selinux
Disable SELinux context support.
--xattrs
Enable extended attributes support.
--no-xattrs
Disable extended attributes support.
--xattrs-exclude=PATTERN
Specify the exclude pattern for xattr keys. PATTERN is a glob‐
bing pattern, e.g. --xattrs-exclude='user.*' to include only at‐
tributes from the user namespace.
--xattrs-include=PATTERN
Specify the include pattern for xattr keys. PATTERN is a glob‐
bing pattern.
Device selection and switching
-f, --file=ARCHIVE
Use archive file or device ARCHIVE. If this option is not given,
tar will first examine the environment variable `TAPE'. If it is
set, its value will be used as the archive name. Otherwise, tar
will assume the compiled-in default. The default value can be
inspected either using the --show-defaults option, or at the end
of the tar --help output.
An archive name that has a colon in it specifies a file or device
on a remote machine. The part before the colon is taken as the
machine name or IP address, and the part after it as the file or
device pathname, e.g.:
--file=remotehost:/dev/sr0
An optional username can be prefixed to the hostname, placing a @
sign between them.
By default, the remote host is accessed via the rsh(1) command.
Nowadays it is common to use ssh(1) instead. You can do so by
giving the following command line option:
--rsh-command=/usr/bin/ssh
The remote machine should have the rmt(8) command installed. If
its pathname does not match tar's default, you can inform tar
about the correct pathname using the --rmt-command option.
--force-local
Archive file is local even if it has a colon.
-F, --info-script=COMMAND, --new-volume-script=COMMAND
Run COMMAND at the end of each tape (implies -M). The command
can include arguments. When started, it will inherit tar's envi‐
ronment plus the following variables:
TAR_VERSION
GNU tar version number.
TAR_ARCHIVE
The name of the archive tar is processing.
TAR_BLOCKING_FACTOR
Current blocking factor, i.e. number of 512-byte blocks in
a record.
TAR_VOLUME
Ordinal number of the volume tar is processing (set if
reading a multi-volume archive).
TAR_FORMAT
Format of the archive being processed. One of: gnu,
oldgnu, posix, ustar, v7.
TAR_SUBCOMMAND
A short option (with a leading dash) describing the opera‐
tion tar is executing.
TAR_FD File descriptor which can be used to communicate the new
volume name to tar.
If the info script fails, tar exits; otherwise, it begins writing
the next volume.
-L, --tape-length=N
Change tape after writing Nx1024 bytes. If N is followed by a
size suffix (see the subsection Size suffixes below), the suffix
specifies the multiplicative factor to be used instead of 1024.
This option implies -M.
-M, --multi-volume
Create/list/extract multi-volume archive.
--rmt-command=COMMAND
Use COMMAND instead of rmt when accessing remote archives. See
the description of the -f option, above.
--rsh-command=COMMAND
Use COMMAND instead of rsh when accessing remote archives. See
the description of the -f option, above.
--volno-file=FILE
When this option is used in conjunction with --multi-volume, tar
will keep track of which volume of a multi-volume archive it is
working in FILE.
Device blocking
-b, --blocking-factor=BLOCKS
Set record size to BLOCKSx512 bytes.
-B, --read-full-records
When listing or extracting, accept incomplete input records after
end-of-file marker.
-i, --ignore-zeros
Ignore zeroed blocks in archive. Normally two consecutive
512-blocks filled with zeroes mean EOF and tar stops reading af‐
ter encountering them. This option instructs it to read further
and is useful when reading archives created with the -A option.
--record-size=NUMBER
Set record size. NUMBER is the number of bytes per record. It
must be multiple of 512. It can can be suffixed with a size suf‐
fix, e.g. --record-size=10K, for 10 Kilobytes. See the subsec‐
tion Size suffixes, for a list of valid suffixes.
Archive format selection
-H, --format=FORMAT
Create archive of the given format. Valid formats are:
gnu GNU tar 1.13.x format
oldgnu GNU format as per tar <= 1.12.
pax, posix
POSIX 1003.1-2001 (pax) format.
ustar POSIX 1003.1-1988 (ustar) format.
v7 Old V7 tar format.
--old-archive, --portability
Same as --format=v7.
--pax-option=keyword[[:]=value][,keyword[[:]=value]]...
Control pax keywords when creating PAX archives (-H pax). This
option is equivalent to the -o option of the pax(1) utility.
--posix
Same as --format=posix.
-V, --label=TEXT
Create archive with volume name TEXT. If listing or extracting,
use TEXT as a globbing pattern for volume name.
Compression options
-a, --auto-compress
Use archive suffix to determine the compression program.
-I, --use-compress-program=COMMAND
Filter data through COMMAND. It must accept the -d option, for
decompression. The argument can contain command line options.
-j, --bzip2
Filter the archive through bzip2(1).
-J, --xz
Filter the archive through xz(1).
--lzip Filter the archive through lzip(1).
--lzma Filter the archive through lzma(1).
--lzop Filter the archive through lzop(1).
--no-auto-compress
Do not use archive suffix to determine the compression program.
-z, --gzip, --gunzip, --ungzip
Filter the archive through gzip(1).
-Z, --compress, --uncompress
Filter the archive through compress(1).
--zstd Filter the archive through zstd(1).
Local file selection
--add-file=FILE
Add FILE to the archive (useful if its name starts with a dash).
--backup[=CONTROL]
Backup before removal. The CONTROL argument, if supplied, con‐
trols the backup policy. Its valid values are:
none, off
Never make backups.
t, numbered
Make numbered backups.
nil, existing
Make numbered backups if numbered backups exist, simple
backups otherwise.
never, simple
Always make simple backups
If CONTROL is not given, the value is taken from the VERSION_CON‐
TROL environment variable. If it is not set, existing is as‐
sumed.
-C, --directory=DIR
Change to DIR before performing any operations. This option is
order-sensitive, i.e. it affects all options that follow.
--exclude=PATTERN
Exclude files matching PATTERN, a glob(3)-style wildcard pattern.
--exclude-backups
Exclude backup and lock files.
--exclude-caches
Exclude contents of directories containing file CACHEDIR.TAG, ex‐
cept for the tag file itself.
--exclude-caches-all
Exclude directories containing file CACHEDIR.TAG and the file it‐
self.
--exclude-caches-under
Exclude everything under directories containing CACHEDIR.TAG
--exclude-ignore=FILE
Before dumping a directory, see if it contains FILE. If so, read
exclusion patterns from this file. The patterns affect only the
directory itself.
--exclude-ignore-recursive=FILE
Same as --exclude-ignore, except that patterns from FILE affect
both the directory and all its subdirectories.
--exclude-tag=FILE
Exclude contents of directories containing FILE, except for FILE
itself.
--exclude-tag-all=FILE
Exclude directories containing FILE.
--exclude-tag-under=FILE
Exclude everything under directories containing FILE.
--exclude-vcs
Exclude version control system directories.
--exclude-vcs-ignores
Exclude files that match patterns read from VCS-specific ignore
files. Supported files are: .cvsignore, .gitignore, .bzrignore,
and .hgignore.
-h, --dereference
Follow symlinks; archive and dump the files they point to.
--hard-dereference
Follow hard links; archive and dump the files they refer to.
-K, --starting-file=MEMBER
Begin at the given member in the archive.
--newer-mtime=DATE
Work on files whose data changed after the DATE. If DATE starts
with / or . it is taken to be a file name; the mtime of that file
is used as the date.
--no-null
Disable the effect of the previous --null option.
--no-recursion
Avoid descending automatically in directories.
--no-unquote
Do not unquote input file or member names.
--no-verbatim-files-from
Treat each line read from a file list as if it were supplied in
the command line. I.e., leading and trailing whitespace is re‐
moved and, if the resulting string begins with a dash, it is
treated as tar command line option.
This is the default behavior. The --no-verbatim-files-from op‐
tion is provided as a way to restore it after --verba‐
tim-files-from option.
This option is positional: it affects all --files-from options
that occur after it in, until --verbatim-files-from option or end
of line, whichever occurs first.
It is implied by the --no-null option.
--null Instruct subsequent -T options to read null-terminated names ver‐
batim (disables special handling of names that start with a
dash).
See also --verbatim-files-from.
-N, --newer=DATE, --after-date=DATE
Only store files newer than DATE. If DATE starts with / or . it
is taken to be a file name; the mtime of that file is used as the
date.
--one-file-system
Stay in local file system when creating archive.
-P, --absolute-names
Don't strip leading slashes from file names when creating
archives.
--recursion
Recurse into directories (default).
--suffix=STRING
Backup before removal, override usual suffix. Default suffix is
~, unless overridden by environment variable SIMPLE_BACKUP_SUF‐
FIX.
-T, --files-from=FILE
Get names to extract or create from FILE.
Unless specified otherwise, the FILE must contain a list of names
separated by ASCII LF (i.e. one name per line). The names read
are handled the same way as command line arguments. They undergo
quote removal and word splitting, and any string that starts with
a - is handled as tar command line option.
If this behavior is undesirable, it can be turned off using the
--verbatim-files-from option.
The --null option instructs tar that the names in FILE are sepa‐
rated by ASCII NUL character, instead of LF. It is useful if the
list is generated by find(1) -print0 predicate.
--unquote
Unquote file or member names (default).
--verbatim-files-from
Treat each line obtained from a file list as a file name, even if
it starts with a dash. File lists are supplied with the
--files-from (-T) option. The default behavior is to handle
names supplied in file lists as if they were typed in the command
line, i.e. any names starting with a dash are treated as tar op‐
tions. The --verbatim-files-from option disables this behavior.
This option affects all --files-from options that occur after it
in the command line. Its effect is reverted by the --no-verba‐
tim-files-from option.
This option is implied by the --null option.
See also --add-file.
-X, --exclude-from=FILE
Exclude files matching patterns listed in FILE.
File name transformations
--strip-components=NUMBER
Strip NUMBER leading components from file names on extraction.
--transform=EXPRESSION, --xform=EXPRESSION
Use sed replace EXPRESSION to transform file names.
File name matching options
These options affect both exclude and include patterns.
--anchored
Patterns match file name start.
--ignore-case
Ignore case.
--no-anchored
Patterns match after any / (default for exclusion).
--no-ignore-case
Case sensitive matching (default).
--no-wildcards
Verbatim string matching.
--no-wildcards-match-slash
Wildcards do not match /.
--wildcards
Use wildcards (default for exclusion).
--wildcards-match-slash
Wildcards match / (default for exclusion).
Informative output
--checkpoint[=N]
Display progress messages every Nth record (default 10).
--checkpoint-action=ACTION
Run ACTION on each checkpoint.
--clamp-mtime
Only set time when the file is more recent than what was given
with --mtime.
--full-time
Print file time to its full resolution.
--index-file=FILE
Send verbose output to FILE.
-l, --check-links
Print a message if not all links are dumped.
--no-quote-chars=STRING
Disable quoting for characters from STRING.
--quote-chars=STRING
Additionally quote characters from STRING.
--quoting-style=STYLE
Set quoting style for file and member names. Valid values for
STYLE are literal, shell, shell-always, c, c-maybe, escape, lo‐
cale, clocale.
-R, --block-number
Show block number within archive with each message.
--show-omitted-dirs
When listing or extracting, list each directory that does not
match search criteria.
--show-transformed-names, --show-stored-names
Show file or archive names after transformation by --strip and
--transform options.
--totals[=SIGNAL]
Print total bytes after processing the archive. If SIGNAL is
given, print total bytes when this signal is delivered. Allowed
signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2. The
SIG prefix can be omitted.
--utc Print file modification times in UTC.
-v, --verbose
Verbosely list files processed. Each instance of this option on
the command line increases the verbosity level by one. The maxi‐
mum verbosity level is 3. For a detailed discussion of how vari‐
ous verbosity levels affect tar's output, please refer to GNU Tar
Manual, subsection 2.5.2 "The '--verbose' Option".
--warning=KEYWORD
Enable or disable warning messages identified by KEYWORD. The
messages are suppressed if KEYWORD is prefixed with no- and en‐
abled otherwise.
Multiple --warning options accumulate.
Keywords controlling general tar operation:
all Enable all warning messages. This is the default.
none Disable all warning messages.
filename-with-nuls
"%s: file name read contains nul character"
alone-zero-block
"A lone zero block at %s"
Keywords applicable for tar --create:
cachedir
"%s: contains a cache directory tag %s; %s"
file-shrank
"%s: File shrank by %s bytes; padding with zeros"
xdev "%s: file is on a different filesystem; not dumped"
file-ignored
"%s: Unknown file type; file ignored"
"%s: socket ignored"
"%s: door ignored"
file-unchanged
"%s: file is unchanged; not dumped"
ignore-archive
"%s: archive cannot contain itself; not dumped"
file-removed
"%s: File removed before we read it"
file-changed
"%s: file changed as we read it"
failed-read
Suppresses warnings about unreadable files or directories.
This keyword applies only if used together with the --ig‐
nore-failed-read option.
Keywords applicable for tar --extract:
existing-file
"%s: skipping existing file"
timestamp
"%s: implausibly old time stamp %s"
"%s: time stamp %s is %s s in the future"
contiguous-cast
"Extracting contiguous files as regular files"
symlink-cast
"Attempting extraction of symbolic links as hard links"
unknown-cast
"%s: Unknown file type '%c', extracted as normal file"
ignore-newer
"Current %s is newer or same age"
unknown-keyword
"Ignoring unknown extended header keyword '%s'"
decompress-program
Controls verbose description of failures occurring when
trying to run alternative decompressor programs. This
warning is disabled by default (unless --verbose is used).
A common example of what you can get when using this warn‐
ing is:
$ tar --warning=decompress-program -x -f archive.Z
tar (child): cannot run compress: No such file or directory
tar (child): trying gzip
This means that tar first tried to decompress archive.Z
using compress, and, when that failed, switched to gzip.
record-size
"Record size = %lu blocks"
Keywords controlling incremental extraction:
rename-directory
"%s: Directory has been renamed from %s"
"%s: Directory has been renamed"
new-directory
"%s: Directory is new"
xdev "%s: directory is on a different device: not purging"
bad-dumpdir
"Malformed dumpdir: 'X' never used"
-w, --interactive, --confirmation
Ask for confirmation for every action.
Compatibility options
-o When creating, same as --old-archive. When extracting, same as
--no-same-owner.
Size suffixes
Suffix Units Byte Equivalent
b Blocks SIZE x 512
B Kilobytes SIZE x 1024
c Bytes SIZE
G Gigabytes SIZE x 1024^3
K Kilobytes SIZE x 1024
k Kilobytes SIZE x 1024
M Megabytes SIZE x 1024^2
P Petabytes SIZE x 1024^5
T Terabytes SIZE x 1024^4
w Words SIZE x 2
RETURN VALUE
Tar's exit code indicates whether it was able to successfully perform
the requested operation, and if not, what kind of error occurred.
0 Successful termination.
1 Some files differ. If tar was invoked with the --compare
(--diff, -d) command line option, this means that some files in
the archive differ from their disk counterparts. If tar was
given one of the --create, --append or --update options, this
exit code means that some files were changed while being archived
and so the resulting archive does not contain the exact copy of
the file set.
2 Fatal error. This means that some fatal, unrecoverable error oc‐
curred.
If a subprocess that had been invoked by tar exited with a nonzero exit
code, tar itself exits with that code as well. This can happen, for ex‐
ample, if a compression option (e.g. -z) was used and the external com‐
pressor program failed. Another example is rmt failure during backup to
a remote device.
SEE ALSO
bzip2(1), compress(1), gzip(1), lzma(1), lzop(1), rmt(8), symlink(7),
xz(1), zstd(1).
Complete tar manual: run info tar or use emacs(1) info mode to read it.
Online copies of GNU tar documentation in various formats can be found
at:
https://www.gnu.org/software/tar/manual
BUG REPORTS
Report bugs to <[email protected]>.
COPYRIGHT
Copyright © 2023 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/li‐
censes/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
TAR July 11, 2022 TAR(1)