一、基本用法

参数:

-c :建立一个压缩文件

-x :解开一个压缩文件

-t :查看压缩包里面的文件



二、压缩

场景:

# tree /var/www
/var/www
├── blog
│   ├── index.php
│   ├── update
│   │   └── a.txt
│   └── websource
│       └── blog.html
├── cms
│   ├── index.php
│   ├── update
│   │   └── b.txt
│   └── websource
│       └── home.html
├── license.txt
└── log
    └── 20150429.log


1.打包目录blog,其中压缩文件test1.tar.gz中会有/var/www/*目录前缀

# tar -zcvf /var/www/test1.tar.gz /var/www/blog
tar: Removing leading `/' from member names
/var/www/blog/
/var/www/blog/index.php
/var/www/blog/update/
/var/www/blog/update/a.txt
/var/www/blog/websource/
/var/www/blog/websource/blog.html


2.去掉目录前缀

①进入blog目录,其中压缩文件test2.tar.gz中连blog目录也被去除

# cd /var/www/blog
# tar -zcvf /var/www/test2.tar.gz ./
./
./index.php
./update/
./update/a.txt
./websource/
./websource/blog.html


②进入blog目录的上层目录/var/www

# cd /var/www
# tar -zcvf /var/www/test3.tar.gz blog
blog/
blog/index.php
blog/update/
blog/update/a.txt
blog/websource/
blog/websource/blog.html

注意:如果要同时打包blog目录和cms目录

# tar -zcvf /var/www/test4.tar.gz blog cms
blog/
blog/index.php
blog/update/
blog/update/a.txt
blog/websource/
blog/websource/blog.html
cms/
cms/index.php
cms/update/
cms/update/b.txt
cms/websource/
cms/websource/home.html


③如果不想cd到相当目录,加-C参数,-C 是临时切换工作目录

# pwd
/
# tar -zcvf /var/www/test5.tar.gz -C /var/www blog
blog/
blog/index.php
blog/update/
blog/update/a.txt
blog/websource/
blog/websource/blog.html


# tar -zcvf /var/www/test6.tar.gz -C /var/www/blog ./
./
./index.php
./update/
./update/a.txt
./websource/
./websource/blog.html


3.压缩某目录时排除某些目录或文件

tar -zcvf **.tar.gz --exclude=XX YY 注意XX与YY要么同时是相对路径,要么同时是绝对路径,否则并不能排除目录或文件

 e.g 压缩除cms外/var/www目录下所有的文件

①相对路径

# cd /var
# tar -zcvf /var/www/test7.tar.gz --exclude=www/cms www

②绝对路径

# pwd
/
# tar -zcvf /var/www/test8.tar.gz --exclude=/var/www/cms /var/www

注意:/var/www/cms后面不能有/



三、解压

从第二部分压缩的实验可以看出,命令tar [OPTION...] [FILE]...其中[FILE]默认在当前目录

  1. 解压到当前目录

# pwd
/
# tar -zxvf /var/www/test5.tar.gz

2.解压到指定目录

# pwd
/
# tar -zxvf /var/www/test5.tar.gz -C /home

3.解压压缩文件中指定目录或文件

# tar -zxvf /var/www/test4.tar.gz -C /home blog
# tar -zxvf /var/www/test4.tar.gz -C /home blog/index.php