Linux Shell脚本_备份文件的批量删除 1.0


最近师傅要求写一个Linux Shell脚本,这个以前从来没接触过,自己就在周末研究了一天,虽然代码现在看起来简单,但是毕竟第一次接触,花了好多时间,好了,开始正题:

这个脚本的功能主要是删除没有用的备份文件,条件是保留最新两天的文件,其他的全部删除

比如说有1号到10号的文件,那么就保留9号,10号两天的文件,其他的全部删除

看代码:

 
  1. #!/bin/sh   
  2. echo "begin deleting"  
  3. #进入备份文件夹下   
  4. cd back_up/   
  5. #取得最新文件及其时间   
  6. lastestfile=`ls -t|head -n1`   
  7. lastestdate=`ls -la $lastestfile --time-style '+%Y%m%d'| awk '{print$6}'`   
  8. ((lastestdate=lastestdate-1));   
  9. while true  
  10. do  
  11. #取得最老的文件及其时间   
  12.         oldfile=`ls -rt|head -n1`   
  13.         olddate=`ls -la $oldfile --time-style '+%Y%m%d'| awk '{print$6}'`   
  14.         if [ "$lastestdate" -eq "$olddate" ]; then   
  15. #删除完毕,退出循环   
  16.                 exit 0   
  17.         fi   
  18.         if [ "$lastestdate" -gt "$olddate" ]; then   
  19.                 rm $oldfile   
  20.         fi   
  21. done  

这段代码很简单,由于之前没写过shell,所以周末研究了一天,顺便把linux的命令也熟悉了一下,感觉收获很多

学到的相关的命令:

touch -d "3 days ago" onefile   ----->把onefile文件的时间修改为3天前

ls -lt --time-style  '+%Y%m%d-%H%M%s'   ----->按照规定的形式显示文件日期  www.bkjia.com还可以设置环境变量修改默认显示

awk命令  print$6 ---->显示第六列的内容   (单列显示文件信息)

ls -lt 新-->旧显示   ls -rt  -->旧-->新显示、

ls -t|head -n1 -----> 显示最新的那个文件

相关内容