Linux下文档的压缩和打包命令(2)

可以打包目录也可以打包文件
语法:tar [-zjxcvfpP] filename
打包: tar -cvf  test.tar  test 其中test是文件或目录
-c    表示建立包
-v    可视化打包的过程
-f    压缩时跟 “-f 文件名”,意思是压缩后的文件名为filename, 解压时跟 “-f 文件名”,意思是解压filename. 请注意,如果是多个参数组合的情况下带有 “-f”,请把 “-f” 写到最后面。
-z    打包的同时使用gzip压缩
-j    打包的同时使用bzip2压缩
-J    打包的同时使用xz压缩
-C    指定解压后的目录
tar -C /tmp/ -xvf 1.tar    解压到指定目录/tmp里面

查看包内容: tar -tf  test.tar
-t    查看tar包里面的文件
同样使用 tar -tf 查看压缩的包: tar -tf 1.tar.gz 或者tar -tf 1.tar.bz2

解包: tar -xvf  test.tar
-x    解包或者解压缩
不管是打包还是解包,原来的文件是不会删除的,但它会覆盖当前已经存在的文件或者目录。

打包abc目录为abc.tar,查看abc.tar的内容,解压abc.tar包;

[root@localhost tmp]# ls -l
drwxr-xr-x. 2 root root    4096 Mar 27 15:27 abc
-rw-------. 1 root root 16965117 Mar 26 13:00 a.img
-rwxr-xr-x. 1 root root 13506560 Mar 26 12:58 dhcp-4.3.1.tar
[root@localhost tmp]# tar -cvf abc.tar abc
abc/
abc/passwd
abc/a.img
[root@localhost tmp]# tar -tf abc.tar 
abc/
abc/passwd
abc/a.img
[root@localhost tmp]# tar -xvf abc.tar 
abc/
abc/passwd
abc/a.img

同时打包多个文件到11.tar
[root@localhost tmp]# tar -cvf 11.tar abc a.img dhcp-4.3.1.tar abc.tar 
abc/
abc/passwd
abc/a.img
a.img
dhcp-4.3.1.tar
abc.tar
[root@localhost tmp]# ls -lh
-rw-r--r--. 1 root root  62M Mar 27 16:33 11.tar


打包的同时使用gzip压缩: tar -czvf  1.tar.gz 1 其中1可以是文件也可以是目录
-z 表示打包同时使用gzip压缩
解压.tar.gz的压缩包: tar -xzvf 1.tar.gz
使用bzip2压缩: tar -cjvf 1.tar.bz2 1
-j 表示打包同时使用bzip2压缩
解压.tar.bz2: tar -xjvf 1.tar.bz2


使用gzip压缩并打包,使用bzip2压缩并打包,对比2种压缩格式,bzip2压缩后的文件更小;使用xz压缩,压缩效果最佳!压缩后文件最小!
源文件为13M,gzip压缩后为8.6M,bzip2压缩后为8.4M,xz压缩后为8.0M;

[root@localhost tmp]# ls -lh
-rwxr-xr-x. 1 root root  13M Mar 26 12:58 dhcp-4.3.1.tar
[root@localhost tmp]# tar -czvf gzip.tar.gz dhcp-4.3.1.tar dhcp-4.3.1.tar
[root@localhost tmp]# tar -cjvf bzip2.tar.bz2 dhcp-4.3.1.tar dhcp-4.3.1.tar
[root@localhost tmp]# ls -lh
-rw-r--r--. 1 root root 8.4M Mar 27 16:54 bzip2.tar.bz2
-rwxr-xr-x. 1 root root  13M Mar 26 12:58 dhcp-4.3.1.tar
-rw-r--r--. 1 root root 8.6M Mar 27 16:54 gzip.tar.gz
[root@localhost tmp]# xz dhcp-4.3.1.tar 
[root@localhost tmp]# ls -lh
-rw-r--r--. 1 root root 8.4M Mar 27 16:54 bzip2.tar.bz2
-rwxr-xr-x. 1 root root 8.0M Mar 26 12:58 dhcp-4.3.1.tar.xz
-rw-r--r--. 1 root root 8.6M Mar 27 16:54 gzip.tar.gz

有时我们会看到一种后缀名为 .tar.xz的文件,这种压缩包是用xz工具压缩,

打包压缩成 xz格式压缩包:tar -cJvf dir.tar.xz  dir/
解压的方法为:tar -Jxvf  file.tar.xz

可以在打包的时候,排除某些文件或者目录添加参数    --exclude
tar --exclude 1.txt  -czvf 1.tar.gz  dir/
排除多个文件或者目录: tar --exclude "目录名" --exclude "*文件名"  -czvf 1.tar.gz  dir/

打包root目录到1.tar.gz 并排除目录里面的install开头的文件;

[root@localhost ~]# tar -czvf 1.tar.gz --exclude "install*" /root/

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/16450.html