打包压缩三剑客:tar、gzip、zip(unzip)
1、概述
tar 大部分使用tar即可,创建、查看、解压到指定目录
gzip 一般配合其他命令使用
zip、unzip 一般用于解压zip格式的压缩包
2、tar
tar命令使用:
创建zcf:tar zcf 压缩包名称 被压缩的文件或目录
查看tf:tar tf 压缩包名
解压xf:tar xf 压缩包名。默认解压到当前目录
选项:
v:verbose,显示过程
c:create,创建包(打包),如果只用cf,则是打包,不压缩
z:gzip,tar命令创建包后,通过gzip压缩工具进行压缩。所以,tar打包 gz压缩,扩展名:.tar.gz
j:使用bzip2进行压缩,扩展名:.tar.bz2
J:使用xz进行压缩,扩展名:.tar.xz
f:file,指定压缩包,f选项一般放在其他选项的最后
x:extract,解压
案例1、创建压缩包。把/etc/目录压缩放到/root/目录中,名为etc.tar.gz
[root@linux-87-01 ~]# tar zcf etc.tar.gz /etc
tar: Removing leading `/' from member names
[root@linux-87-01 ~]# ll
total 10260
-rw-r--r--. 1 root root 3 May 5 20:59 1.txt
-rw-------. 1 root root 1455 Apr 21 23:32 anaconda-ks.cfg
-rw-r--r--. 1 root root 10491933 May 5 21:17 etc.tar.gz
-rw-r--r--. 1 root root 986 May 3 21:27 passwd
[root@linux-87-01 ~]#
会提示:tar: Removing leading `/’ from member names
这是个警告而已,可以忽略。
产生的原因:
这是tar命令的安全保护机制
提示出现的原因,打包的目标目录或文件是绝对路径
把使用的绝对路径转换为相对路径
为了防止压缩包中保留绝对路径,解压的时候可能发生覆盖,导致数据、配置丢失。
使用相对路径打包,就不会警告,或者可以使用-P选项去掉警告,如:
[root@linux-87-01 ~]# tar zcfP /tmp/etc.tar.gz /etc/
[root@linux-87-01 ~]#
注意:实际中,为了安全,使用相对路径打包
案例2:查看压缩包。
[root@linux-87-01 ~]# tar tf /tmp/etc.tar.gz
tar: Removing leading `/' from member names
/etc/
/etc/fstab
.......
同样地,不使用P选项,也会有警告信息。
案例3:解压包。 把/tmp/etc.tar.gz包解压到/root/目录中
[root@linux-87-01 ~]# tar xf /tmp/etc.tar.gz -C /root/
tar: Removing leading `/' from member names
[root@linux-87-01 ~]# ls
anaconda-ks.cfg etc passwd
[root@linux-87-01 ~]#
解压语法:
解压到当前目录:tar xf 压缩包名
解压到指定目录:tar xf 压缩包名 -C 目标目录
3、gzip
创建gz压缩包
[root@linux-87-01 ~]# gzip 1.txt
[root@linux-87-01 ~]# ls
1.txt.gz anaconda-ks.cfg passwd
[root@linux-87-01 ~]#
解压(-d)
[root@linux-87-01 ~]# gzip -d 1.txt.gz
[root@linux-87-01 ~]# ls
1.txt anaconda-ks.cfg passwd
[root@linux-87-01 ~]#
4、zip、unzip
专门处理zip格式的压缩包,tar无法处理zip格式的压缩包
.zip格式是Linux和Windows都支持的格式
压缩:
-r选项,用于压缩目录
压缩文件:
[root@linux-87-01 ~]# zip 1.txt.gz 1.txt
adding: 1.txt (stored 0%)
[root@linux-87-01 ~]# ls
1.txt 1.txt.gz anaconda-ks.cfg passwd
[root@linux-87-01 ~]#
压缩目录:
[root@linux-87-01 ~]# zip -r etc.zip /etc/
解压:
[root@linux-87-01 ~]# unzip etc.zip
unzip -t 压缩包:查看压缩包有哪些文件