1. 打包和压缩文件
linux下目前常用gzip和bzip2来压缩文件,tar打包文件。
常用扩展名:
*.gz gzip压缩的文件
*.bz2 bzip2压缩的文件
*.tar tar打包的文件,没有压缩
*.tar.gz tar打包文件,经过gzip压缩
*.tar.bz2 tar打包文件,经过bzip2压缩
2. gzip压缩
gzip是使用最广的压缩命令。用来代替compress压缩。
$ gzip -h
gzip 1.3.3
(2002-03-08)
usage: gzip [-cdfhlLnNrtvV19] [-S suffix] [file ...]
常用参数
-c : 压缩数据输出到屏幕,可重定向处理
-d : 解压缩
-t : 检验压缩文件的一致性,看看文件是否错误
-v : 显示压缩的详细信息,压缩比等
-# : 数字,压缩等级,1-9,9压缩率最高,默认6
压缩文件
$ gzip -v test
test: 53.1% -- replaced with test.gz
压缩会删掉本地文件,新建test.gz文件
不删除文件使用重定向
$ gzip -c test > test.gz
查看压缩后的文件内容,不解压缩的情况下,使用zcat命令
$ zcat test.gz
3. bzip2
bzip2是用来代替gzip的压缩,比gzip压缩比例还高,使用参数几乎和gzip相同。
$ bzip2 -h
bzip2, a block-sorting file compressor. Version 1.0.2, 30-Dec-2001.
usage: bzip2 [flags and input files in any order]
常用参数
-c : 压缩数据输出到屏幕,可重定向处理
-d : 解压缩
-k : 保留原文件
-z : 压缩
-t : 检验压缩文件的一致性,看看文件是否错误
-v : 显示压缩的详细信息,压缩比等
-# : 数字,压缩等级,1-9,9压缩率最高,默认6
使用
#压缩test文件,生成test.bz2
$ bzip2 -z test
#保留原文件, 压缩生成test.bz2
$ bzip2 -k test
#解压缩文件
$ bzip2 -d test.bz2
查看压缩文件内容,使用bzcat
$ bzcat test.bz2
3. 打包:tar
tar为打包命令,将多个文件打包成一个文件。
还包含压缩参数。
$ tar --help
GNU `tar' saves many files together into a single tape or disk archive, and
can restore individual files from the archive.
Usage: tar [OPTION]... [FILE]...
Examples:
tar -cf archive.tar foo bar # Create archive.tar from files foo and bar.
tar -tvf archive.tar # List all files in archive.tar verbosely.
tar -xf archive.tar # Extract all files from archive.tar.
#参数
-c 新建压缩文件
-t 列出压缩文件列表
-x 解压缩文件
-c,-t,-x不能同时出现
-j 通过bzip2来压缩或解压缩,文件名最好为. *.tar.bz2
-z 通过gzip压缩或解压缩, 文件名最好为 *.tar.gz
-v 展示正在处理的详细信息
-f 后面跟要被处理的文件名
-C 解压时,后面跟解压到的目录名
-p 保留文件的原本权限
-P 保留绝对路径
--exclude=FILE 排除FILE文件
tar的基本用法
#创建bzip2压缩文件
$ tar -jcv -f test.tar.bz2 test/
test/
test/1
test/10
#创建gzip压缩文件
$ tar -zcv -f test.tar.gz test
test/
test/1
test/10
#查看文件
$ ll
drwxrwxr-x 2 work work 4096 Jul 19 19:12 test
-rw-rw-r-- 1 work work 61897 Jul 19 19:13 test.tar.bz2
#不解压缩情况下查看文件列表
$ tar -jtv -f test.tar.bz2
tar: Record size = 8 blocks
drwxrwxr-x work/work 0 2014-07-19 19:12:40 test/
-rw-rw-r-- work/work 6353 2014-07-19 19:12:40 test/1
-rw-rw-r-- work/work 6343 2014-07-19 19:12:40 test/10
#解压缩到当前目录
$ tar -jxv -f test.tar.bz2
test/
test/1
test/10
#解压缩到指定目录test2
$ mkdir test2
$ tar -jxv -f test.tar.bz2 -C test2
test/
test/1
test/10
#保留原文件权限
$ tar -zcvp -f etc.tar.gz /etc
#查看压缩文件
$ tar -ztv -f etc.tar.gz
打包时不包含某个文件
#创建压缩文件,不包含某个文件test/10
$ tar -zcv -f test.tar.gz --exclude=test/10 test/*
test/1
备份比某个时刻更新的文件
$ tar -zcv -f etc.tar.gz --newer-mtime="2013/10/31" /etc/*
/etc/xinetd.d/
tar: /etc/yp.conf: file is unchanged; not dumped
#not dumpd表示没有备份的