tar 命令
使用tar命令进行归档,将多个文件或者文件夹打包到一个文件,然后对归档文件进行压缩。
归档格式
.tar -->进行归档,不进行压缩
.tar.gz -->先归档,再用gzip进行压缩
.tar.xz -->先归档,再用xz进行压缩
.tar.bz2–>先归档,再用bz2进行压缩
常用命令选项
-c:创建.tar格式的包文件
-x:解开.tar格式的包文件
-v:输出详细信息
-f:表示使用归档文件
-t:列表查看包内文件
-p:保持原文件的原来属性
-P:保持原文件的绝对路径
-z:调用gzip去压缩
-J:调用xz去压缩
-j:调用bzip2去压缩
用例
1.打压缩包
将当前目录下的passwd文件打包成passwd.tar.gz压缩包,先复制一个文件和一个目录
[root@localhost tar_practice]# cp /etc/passwd .
[root@localhost tar_practice]# cp /boot . -r
[root@localhost tar_practice]# ls
boot passwd
[root@localhost tar_practice]# tar czf passwd.tar.gz passwd
[root@localhost tar_practice]# ls
boot passwd passwd.tar.gz
2.使用绝对路径进行打压缩包
[root@localhost tar_practice]# tar czf /lianxi/pass.tar.gz /etc/passwd
tar: 从成员名中删除开头的“/”
[root@localhost tar_practice]# ls /lianxi/
pass.tar.gz
这里提示"/“的原因为了防止压缩时/etc文件会覆盖当前目录文件,但在解压缩时会自动去除”/"
3.查看压缩文件的内容使用tf
[root@localhost tar_practice]# tar tf passwd.tar.gz
passwd
4.解压文件使用xf
如果解压文件的时候,不指定路径,默认解压到当前
[root@localhost tar_practice]# tar xf passwd.tar.gz
[root@localhost tar_practice]# ls
boot passwd passwd.tar.bz2 passwd.tar.gz passwd.tar.xz
使用-C选项指定解压的路径,当前解压到练习目录下的test文件夹中
[root@localhost tar_practice]# tar xf /lianxi/pass.tar.gz -C /lianxi/test/
[root@localhost tar_practice]# ls /lianxi/test/
etc
5.将文件和文件夹一起打包压缩
[root@localhost tar_practice]# tar czf /lianxi/test/mix_file_dir.tar.gz /boot /var/log
tar: 从成员名中删除开头的“/”
[root@localhost tar_practice]# ls /lianxi/test/
etc mix_file_dir.tar.gz
6.如果不想打包目录下的其他文件,使用–exclude
[root@localhost test]# tar --exclude=/boot/grub2 -czf /lianxi/test/no_grub2_boot.tar.gz /boot
当有多个文件时,使用{}将不需要的文件包含进来
[root@localhost test]# tar --exclude=/boot/{grub2,efi} -czf /lianxi/test/no_grub2_boot.tar.gz /boot
压缩时嵌入时间
date命令
常用命令选项
+%Y year 年
+%m month 月
+%d day 日
+%H hour 小时
+%M minute 分钟
+%S second 秒
查看时间显示当前格式为xxxx-xx-xx格式,例如2023-01-02
[root@localhost test]# date +%Y-%m-%d
2023-01-15
嵌入时间
使用$符号引用命令执行的结果
[root@localhost test]# tar czf boot-$(date +%Y-%m-%d).tar.gz /boot
tar: 从成员名中删除开头的“/”
[root@localhost test]# ls
boot-2023-01-15.tar.gz etc mix_file_dir.tar.gz no_grub2_boot.tar.gz