最近师傅要求写一个Linux Shell脚本,这个以前从来没接触过,自己就在周末研究了一天,虽然代码现在看起来简单,但是毕竟第一次接触,花了好多时间,好了,开始正题:这个脚本的功能主要是删除没有用的备份文件,条件是保留最新两天的文件,其他的全部删除比如说有1号到10号的文件,那么就保留9号,10号两天的文件,其他的全部删除看代码:
- #!/bin/sh
- echo "begin deleting"
- #进入备份文件夹下
- cd back_up/
- #取得最新文件及其时间
- lastestfile=`ls -t|head -n1`
- lastestdate=`ls -la $lastestfile --time-style "+%Y%m%d"| awk "{print$6}"`
- ((lastestdate=lastestdate-1));
- while true
- do
- #取得最老的文件及其时间
- oldfile=`ls -rt|head -n1`
- olddate=`ls -la $oldfile --time-style "+%Y%m%d"| awk "{print$6}"`
- if [ "$lastestdate" -eq "$olddate" ]; then
- #删除完毕,退出循环
- exit 0
- fi
- if [ "$lastestdate" -gt "$olddate" ]; then
- rm $oldfile
- fi
- done
这段代码很简单,由于之前没写过shell,所以周末研究了一天,顺便把linux的命令也熟悉了一下,感觉收获很多学到的相关的命令: touch -d "3 days ago" onefile ----->把onefile文件的时间修改为3天前ls -lt --time-style "+%Y%m%d-%H%M%s" ----->按照规定的形式显示文件日期 www.linuxidc.com还可以设置环境变量修改默认显示awk命令 print$6 ---->显示第六列的内容 (单列显示文件信息)ls -lt 新-->旧显示 ls -rt -->旧-->新显示、ls -t|head -n1 -----> 显示最新的那个文件