【Linux】tar命令详解

tar命令既可以将多个文件打包成一个归档文件,也可以从归档文件中提取单个文件。

示例:
tar -cf archive.tar foo bar # 将foo和bar文件打包成archive.tar
tar -tvf archive.tar # 查看archive.tar中的所有文件
tar -xf archive.tar # 提取archive.tar中所有文件

主操作模式

-A, --catenate, --concatenate: 将另一个tar中的文件合并到指定tar文件中,如果指定tar文件没有则创建

ubuntu@ubuntu-virtual-machine:~/projects$ tar tf archive.tar 
foo
bar
ubuntu@ubuntu-virtual-machine:~/projects$ tar tf archive1.tar 
foo1
bar1
ubuntu@ubuntu-virtual-machine:~/projects$ tar Af archive.tar archive1.tar 
ubuntu@ubuntu-virtual-machine:~/projects$ tar tf archive.tar 
foo
bar
foo1
bar1

-c, --create:创建新的归档文件

--delete:从归档文件中删除文件

ubuntu@ubuntu-virtual-machine:~/projects$ tar tf archive.tar 
foo
bar
foo1
bar1
ubuntu@ubuntu-virtual-machine:~/projects$ tar --delete -f archive.tar foo bar
ubuntu@ubuntu-virtual-machine:~/projects$ tar tf archive.tar
foo1
bar1

-d, --diff, --compare: 比较归档文件中和文件系统中同名文件的不同

ubuntu@ubuntu-virtual-machine:~/projects$ tar -df archive.tar foo1
foo1: Mod time differs
foo1: Size differs

-r, --apend: 向归档文件中添加新文件

buntu@ubuntu-virtual-machine:~/projects$ tar tf archive.tar
foo1
bar1
ubuntu@ubuntu-virtual-machine:~/projects$ tar rf archive.tar foo bar
ubuntu@ubuntu-virtual-machine:~/projects$ tar tf archive.tar
foo1
bar1
foo
bar

-t, --list: 列出归档文件的所有内容

-u, --update: 仅更新有变化的文件

ubuntu@ubuntu-virtual-machine:~/projects$ ll foo bar
-rw-rw-r-- 1 ubuntu ubuntu 0 May 22 07:17 bar
-rw-rw-r-- 1 ubuntu ubuntu 3 May 22 07:51 foo
ubuntu@ubuntu-virtual-machine:~/projects$ tar tvf archive.tar
-rw-rw-r-- ubuntu/ubuntu     0 2024-05-22 07:17 bar1
-rw-rw-r-- ubuntu/ubuntu     0 2024-05-22 07:17 foo
-rw-rw-r-- ubuntu/ubuntu     0 2024-05-22 07:17 bar
ubuntu@ubuntu-virtual-machine:~/projects$ tar uf archive.tar foo bar
ubuntu@ubuntu-virtual-machine:~/projects$ tar tvf archive.tar
-rw-rw-r-- ubuntu/ubuntu     0 2024-05-22 07:17 bar1
-rw-rw-r-- ubuntu/ubuntu     0 2024-05-22 07:17 foo
-rw-rw-r-- ubuntu/ubuntu     0 2024-05-22 07:17 bar
-rw-rw-r-- ubuntu/ubuntu     3 2024-05-22 07:51 foo

-x, --extract, --get: 从归档文件中提取文件

本地文件名选择

-C, --directory=DIR: 改变工作目录

--exclude=PATTERN: 根据指定模式排除指定文件

ubuntu@ubuntu-virtual-machine:~/projects$ tar tf archive.tar 
bar1
foo
bar
foo
foo2
foo3
ubuntu@ubuntu-virtual-machine:~/projects$ tar xf archive.tar -C temp --exclude=bar*
ubuntu@ubuntu-virtual-machine:~/projects$ ls temp
foo  foo2  foo3

文件名匹配选项(仅对exclude和include生效)

--ignore-case: 忽略大小写

压缩选项

-a, --quto-compress: 根据文件名后缀自动选择压缩算法
-I, --use-compress-program=PROG: 使用指定程序压缩文件
-j, --bzip2: 使用bzip2算法压缩
-J, --xz: 使用xz算法压缩
-z, --gzip, gunzip, ungzip: 使用gzip算法压缩

信息输出

-v, --verbose: 打印详细信息

posted @ 2024-05-22 07:20  NotReferenced  阅读(13)  评论(0编辑  收藏  举报