tar命令

发布时间 2023-04-15 11:11:00作者: 法螺話

1.与windows传文件的软件

  安装lrzsz

[root@localhost lianxi]# yum install lrzsz -y
[root@localhost lianxi]# sz passwd.gz        发送文件到windows --> 将linux系统里的文件传输到windows系统
send 发送
[root@localhost ~]# rz             接受从windows系统里传输文件到linux  
received 接收

2.tar 压缩和解压缩

  1)创建压缩包
  -c 创建一个压缩文件 create
  -f  归档文件
  -z  调用gzip压缩命令去压缩  --》推荐
  -j  调用bz2命令去压缩
  -J  调用xz命令去压缩   -->耗时比较长,压缩效果好

     tar  -czf   压缩文件名.tar.gz    源文件
     tar  -cjf   压缩文件名.tar.bz2    源文件

  tar  -cJf   压缩文件名.tar.xz    源文件

[root@localhost lianxi]# tar  -czf  boot.tar.gz  boot  将当前目录下的boot文件夹打包压缩成boot.tar.gz文件
[root@localhost lianxi]# tar  -cJf  boot.tar.xz  boot 将当前目录下的boot文件夹打包压缩成boot.tar.xz文件
[root@localhost lianxi]# tar cJf  /lianxi/hosts.tar.gz  /etc/hosts
tar: 从成员名中删除开头的“/”

  2)查看压缩包
  -t   list

[root@localhost lianxi]# tar  tf hosts.tar.gz
etc/hosts
[root@localhost lianxi]# tar  -tf hosts.tar.gz
etc/hosts

  3)解压压缩包
      tar  xf     *.tar.gz  *.tar.xz
         -x, --extract, --get
                extract files from an archive
  extract 提取
  archive 归档文件

[root@localhost lianxi]# tar tf shadow.tar.bz2 
etc/shadow
[root@localhost gaohui]# tar  xf  boot.tar.gz  -C  /machi        -C 将压缩文件解压到指定的目录

  创建压缩文件的时候,备份到指定路径,使用绝对路径

[root@localhost machi]# tar  czf  /machi/passwd.tar.gz    /etc/passwd
[root@localhost boot]# tar --exclude=/boot/{grub,grub2,efi}   -czf /machi/no_grub.boot.tar.gz  /boot
tar: 从成员名中删除开头的“/”

  include  包含
  --exclude 排斥出去

练习:

编写一个脚本backup_log.sh实现备份/var/log目录下的所有文件到/scbackup目录下,要求文件名是包含当天日期,精确到秒,文件名例如:20220412200401-log.tar.gz。同时要求删除七天前的备份文件,只保留最近7天的文件。

[root@blueendingnova lianxi]# cat backup_log.sh
#!/bin/bash

ctime=$(date +%Y%m%d%H%M%S)
mkdir -p /scbackup
tar czf /scbackup/${ctime}-log.tar.gz /var/log

find /scbackup -mtime +7 -type f -name "*log.tar.gz" -exec rm -rf {} \;