目标文件格式
tar 命令一般用来将文件归档并压缩,常用的文件格式如下:
*.tar 仅将文件归档,不压缩
*.tar.gz 将文件归档并压缩成 gz 格式
*.tgz 上述格式的简写
*.tar.bz2 将文件归档并压缩成 bz2 格式
常用参数
tar 的参数分为以下四类:
- 主要操作模式:
-A, --catenate, --concatenate append tar files to an archive
-c, --create create a new archive
-d, --diff, --compare find differences between archive and file system
--delete delete from the archive (not on mag tapes!)
-r, --append append files to the end of an archive
-t, --list list the contents of an archive
-u, --update only append files newer than copy in archive
-x, --extract, --get extract files from an archive
- 常用压缩选项
-a, --auto-compress use archive suffix to determine the compression program
-j, --bzip2 filter the archive through bzip2
-z, --gzip, --gunzip, --ungzip filter the archive through gzip
- 操作信息输出:
-v, --verbose verbosely list files processed
- 指定归档的文件名
-f, --file=ARCHIVE use archive file or device ARCHIVE
常用形式
tar 的参数使用即为以下4类参数的组合:
较常用的形式是:
tar [[操作模式][压缩选项]]vf [ARCHIVE] [FILE...]
以 UNIX-style 为例:
- 仅归档
tar -cvf archive_name.tar dirname/ 将指定文件夹归档
tar -xvf archive_name.tar 从 archive 中抽取文件
tar -tvf archive_name.tar 仅罗列 archive 中的文件,但不抽取
tar -rvf archive_name.tar newfile 向archive中添加新文件
tar --delete -vf archive_name.tar oldfile 从archive中删除一个文件
- 归档并压缩成 gz 格式
tar -czvf archive_name.tar.gz dirname/ 将指定文件夹归档,并压缩成gz格式
tar -xzvf archive_name.tar.gz 解压缩,从 archive 中抽取文件
tar -tzvf archive_name.tar.gz 仅罗列 archive 中的文件,但不解压缩和抽取
- 归档并压缩成 bzip2 格式
tar -cjvf archive_name.tar.bz2 dirname/ 将指定文件夹归档,并压缩成 bz2 格式
tar -xjvf archive_name.tar.bz2 解压缩,从 archive 中抽取文件
tar -tjvf archive_name.tar.bz2 仅罗列 archive 中的文件,但不解压缩和抽取
对于压缩后 archive 不能添加和删除某一个文件。
常见错误
错误1
gzip: stdin: not in gzip format
tar: Child returned status 1
tar: Error is not recoverable: exiting now
可能原因是尝试使用 -z 格式解压缩 tar 包。
解决办法:
- 尝试使用如下指令查看文件格式
file <filename>
- 如果输出为
POSIX tar archive (GNU)
, 代表为 tar 格式,使用如下命令解压缩
tar xvf <package_name>
- 如果输出为
gzip compressed data, from Unix, original size modulo
, 代表为 gz 格式,使用如下命令解压缩
tar xzvf <package_name>
原因是
参考: