天天看点

Linux 打包、压缩、解压缩小能手tar命令介绍

作者:海淘世界

在Linux系统管理:使用zip和unzip进行压缩和解压缩中我们介绍了zip命令,不过在Linux的世界中tar命令显然更加出名,使用频率更高。

Linux 打包、压缩、解压缩小能手tar命令介绍

tar 命令支持的选项主要包括:

c create,创建文件
z 使用gzip进行压缩/解压
v verbosely 显示详细信息
f file,指定文件名,必须放在最后
x extrac 解压
j 使用bzip2压缩/解压
t 列出备份文件的内容
C <目的目录>,执行操作前先切换到指定的目录

压缩

比如我们想使用gzip压缩workspace目录,压缩包文件名为workspace1.tar.gz,那么可以输入下面的命令,我们这样理解:创建(create)使用(gzip)压缩的,显示压缩过程(verbosely)的文件(file)workspace.tar.gz,文件名也是惯例,表示这是一个tar(打包)和gzip(压缩)的文件。

注意不要颠倒选项字母的顺序,特别是 f 一定要放在最后,就是这么任性,没办法。对于其它情况,例如解压缩和查看压缩文件内容来说 f 也必须放在最后。

tar -czvf workspace.tar.gz workspace           

解压缩

对于解压来说可以这样理解,请解压缩(extract)这个以(gzip)压缩的,显示压缩过程(verbosely),待解压缩的文件(file)为workspace.tar.gz。

tar -xzvf httpd.tar.gz           

排除文件或者目录

与之前Linux系统管理:使用zip和unzip进行压缩和解压缩一样,排除目录也非常头疼,而且tar的方法与zip还不一样。

tar 使用 --exclude 选项排除目录。

例如想要排除目录1和它下面所有文件,需要添加 --exclude='workspace/1' ,注意不能写成'workspace/1/'

[root@almalinux ~]# tar -czf workspace1.tar.gz --exclude='workspace/1' workspace
[root@almalinux ~]# tar -tzf workspace1.tar.gz
workspace/
workspace/2/
workspace/2/21.txt
workspace/2/22.txt
workspace/3/

// 也可以这样写
[root@almalinux ~]# tar -czf workspace1.tar.gz --exclude=workspace/1 workspace           

或者你想保留目录,但是一般不这样使用。

// 排除目录1下面的所有内容,但是保留目录1,这种不经常用。
[root@almalinux ~]# tar -czf workspace3.tar.gz --exclude='workspace/1/*' workspace
[root@almalinux ~]# tar -tzf workspace3.tar.gz
workspace/
workspace/1/
workspace/2/
workspace/2/21.txt
workspace/2/22.txt
workspace/3/
           

压缩指定目录或者解压到指定文件夹

在压缩文件时,我们希望去掉目录前缀。例如使用下面的命令压缩httpd目录时,压缩包中都带有etc前缀。解压缩时就比较费劲,还需要执行一次拷贝,将httpd目录的内容拷贝到/etc/httpd目录。

# tar -czf httpd.tar.gz /etc/httpd/
tar: Removing leading `/' from member names
# tar -tf httpd.tar.gz
etc/httpd/
etc/httpd/modules
etc/httpd/run
etc/httpd/conf.modules.d/
etc/httpd/conf.modules.d/README
etc/httpd/conf.modules.d/00-optional.conf
etc/httpd/conf.modules.d/10-h2.conf
etc/httpd/conf.modules.d/00-systemd.conf
etc/httpd/conf.modules.d/00-dav.conf
etc/httpd/conf.modules.d/00-base.conf
etc/httpd/conf.modules.d/00-lua.conf
           

此时我们可以使用 -C 选项,在压缩前首先切换到/etc/httpd目录,然后执行压缩。

tar -C /etc/httpd/ -czf httpd.tar.gz .           

同样解压缩时也这样

tar -C /etc/httpd/ -xzf httpd.tar.gz           

完美!

查看压缩包内容

网上下载了一个压缩包,可以通过 -tf 选项查看压缩包的内容。

# tar -tf httpd.tar.gz
./
./README
./php.conf
./autoindex.conf
./userdir.conf
./welcome.conf
           

不过似乎没有办法检查 tar.gz 文件是否损坏,似乎可以通过gzip测试一下:

gzip -t archive.tar.gz           

参考文章

  • https://linuxhandbook.com/tar-exclude-files/
  • https://www.baeldung.com/linux/tar-exclude-files-directories