tar 是 Linux/Unix 系统中用于打包和压缩文件的常用命令。它不仅能创建归档文件,还能结合多种压缩工具使用,完成高效的数据管理任务。以下是 tar 命令的常用参数和一些进阶操作,包括与 split、文件排除等功能。
1. 基本用法
创建归档文件:
tar -cvf archive.tar /path/to/directory
-c:创建一个新的归档文件。
-v:显示归档过程中的详细信息。
-f:指定归档文件名称。
解压归档文件:
tar -xvf archive.tar
-x:解压归档文件。
2. 结合压缩工具
使用 gzip 进行压缩:
tar -czvf archive.tar.gz /path/to/directory
-z:通过 gzip 压缩归档。
使用 bzip2 压缩:
tar -cjvf archive.tar.bz2 /path/to/directory
-j:通过 bzip2 压缩归档。
使用 xz 压缩:
tar -cJvf archive.tar.xz /path/to/directory
-J:使用 xz 压缩,适合需要更高压缩率的场景。
3. 文件分割与大文件操作
当打包的大文件需要分卷存储或传输时,可以结合 split 命令进行分割:
将打包文件按 500MB 大小分割:
tar -cvf - /path/to/directory | split -b 500M - archive.tar.part
该命令将打包后的数据传递给 split,并按每 500MB 切割成多个文件,文件名以 archive.tar.part 开头。
恢复分割文件:
cat archive.tar.part* | tar -xvf -
将分割的文件拼接并解压。
4. 排除文件
在打包时,你可能不希望某些文件或目录包含在归档中,可以通过 --exclude 参数排除它们:
排除单个文件或目录:
tar --exclude=/path/to/exclude -cvf archive.tar /path/to/directory
排除多个文件:
tar --exclude=/path/to/exclude1 --exclude=/path/to/exclude2 -cvf archive.tar /path/to/directory
5. 与 find 配合使用
结合 find 可以按条件打包指定文件:
打包过去 7 天内修改的文件:
find /path/to/directory -type f -mtime -7 | tar -cvf archive.tar -T -
-T - 表示将 find 命令的结果传递给 tar 进行打包。
6. 增量备份
tar 可以使用 --listed-incremental 参数进行增量备份,适合数据更新较频繁的场景。
第一次全量备份:
tar --listed-incremental=snapshot.file -cvf full-backup.tar /path/to/directory
增量备份:
tar --listed-incremental=snapshot.file -cvf incremental-backup.tar /path/to/directory
使用相同的 snapshot.file 来跟踪备份状态。
7. 高级选项与实用技巧
保留符号链接:
tar -cvhf archive.tar /path/to/directory
-h 表示保留符号链接,不会解引用为真实文件。
通过 ssh 进行远程打包:
ssh user@remote "tar -cvf - /path/to/remote/directory" | tar -xvf -
将远程目录打包并直接传输到本地解压。
自定义解压文件权限:
tar --mode='a+rw' -cvf archive.tar /path/to/directory
使用 --mode 选项指定解压后的文件权限。
8. 并行压缩
对于大文件,单线程压缩速度较慢时,可以使用多线程压缩工具如 pigz(并行 gzip)或 pbzip2(并行 bzip2)。
并行压缩:
tar -cvf - /path/to/directory | pigz > archive.tar.gz
并行解压:
pigz -dc archive.tar.gz | tar -xvf -
总结
压缩工具选择:根据需求,选择适合的压缩工具如 gzip、bzip2、xz,在压缩速度和压缩率之间做出平衡。
文件排除与筛选:通过 --exclude 参数和 find 命令,灵活筛选文件,提高备份效率。
文件分割:结合 split 命令,处理大文件的分卷和存储问题。
并行操作:使用多线程压缩工具加速文件压缩和解压。
通过这些进阶技巧,你可以更加高效地使用 tar 命令,处理各种文件归档、备份、传输和解压需求。