返回顶部

shell之for+if嵌套循环结构

shell之for+if嵌套循环结构

学习Python之后,对shell 的for和if循环老是混淆,编写shell脚本加深巩固一下

主要实现两个功能:创建批量目录然后根据时间在每个目录创建年月日日志文件,根据需求删除三个月前的日志文件

批量创建目录和日志文件

复制代码
#!/bin/bash
cd /var/log/cdmone  && mkdir -p bmr   dt  server  hcs  smartx     hcs  storage  winstack

dir=$(ls /var/log/cdmone)
for i in ${dir};do
    for j in {01..30};do
        #touch /var/log/cdmone/${i}/`date +'%Y-%m'-${j}.log`
    for x in {01..12};do
       touch /var/log/cdmone/${i}/`date +%Y-${x}-${j}.log`
    done
    done
done

#ls
/var/log/cdmone
bmr   dt  server  hcs  smartx     hcs  storage  winstack
复制代码

删除指定日期的日志文件

这里没考虑天数(30,31),而是按照月份进行日志处理删除,保留当前日期三个月内的日志

复制代码
#!/bin/bash
cd /var/log/cdmone/wise
Month=$(date +'%Y-%m-%d'|awk -F[-] '{print $2}')
file=$(echo "${Month} - 4" |bc)
if [ ${file} -eq 0 ];then
    file=01
elif [ ${file} -gt 0 ];then
    file=0`echo "${file} + 1" |bc`
elif [ ${file} -lt 0 ];then
    file=$( echo "${file} + 15 - 2" |bc)
fi

logfile=$(date +%Y-${file}-*.log)
find /var/log/cdmone/wise  -type f -name  ${logfile}  |xargs rm -f
复制代码

验证

复制代码
# date +'%Y%m%d'

#bash  rm_file.sh
#find . -type f -name  2022-02-*
./winstack/2022-02-13.log

#调整系统时间进行验证
# date -s '-30 day'
# date +'%Y%m%d'
#bash  rm_file.sh
#find . -type f -name  2022-01-*
复制代码

 

posted @   九尾cat  阅读(2505)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示

目录导航