linux日志定期迁移脚本

find命令格式

find  pathname  --options  [-exec -print -ok ..]
  // 用法:Runtime.getRuntime().exec("命令");
     
    String shpath="/test/test.sh";   //程序路径
    Process process =null;
    String command1 = “chmod 777 ” + shpath;
    try { 
      Runtime.getRuntime().exec(command1 ).waitFor(); 
    } catch (IOException e1) { 
        e1.printStackTrace(); 
    }catch (InterruptedException e) { 
         e.printStackTrace(); 
    }
 
 
    String var="201102";  /参数
    String command2 = “/bin/sh ” + shpath + ” ” + var; 
    Runtime.getRuntime().exec(command2).waitFor();

/**
 * java程序调用shell脚本
 */
public class JavaExecuteShell {
    public static void main(String[] args) {
        try {
            String cmd = "sh /usr/local/app/deploy/test.sh "+args[0] +" "+args[1];
            System.out.println("cmd = "+cmd);
            Process exec = Runtime.getRuntime().exec(cmd);
            String line;
            //要执行的程序可能输出较多,而运行窗口的缓冲区有限,会造成waitFor阻塞,利用这种方式可以在waitFor命令之前读掉输出缓冲区的内容
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            while ((line = bufferedReader.readLine())!=null){
                System.out.println("result======="+line);
            }
            bufferedReader.close();
            //等待脚本执行完成
            exec.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
在linux机器的/usr/local/app/deploy路径下创建名为test.sh的脚本,脚本内容为:

echo i love $1 and $2

find命令参数

pathname:find命令查找的目录路径
-print:find命令将匹配的文件输出到标准输出
-exec:find命令对匹配的文件执行该参数给出的shell命令.格式为: command {} \;
-ok:类似与exec的作用

 

find命令选项

-name:按照文件名进行查找
-perm:按文件权限来查找
-user:按文件的用户主查找
-group:按文件的用户组查找
-type:查找某一类型的文件
	b -- 块设备文件
        d -- 目录
        c -- 字符设备文件
        p -- 管道文件
        l -- 符号链接文件
        f -- 普通文件
-mtime:按照文件的更改时间来查找文件
	-n -- 表示文件更改时间距现在n天以内
        +n -- 表示文件更改时间距现在n天以前

 

日志迁移脚本

使用了find命令的mtime参数,将2个星期前的日志文件统一迁移到指定目录下,有需要的同学可以参考

#!/bin/bash

#1.标准定义
backup_dir="/backup/log"
keep_days=14
week_num=`date +%W`
flag=`expr $week_num % 2`

#2.需要迁移目录
test1="/var/log/nginx/test1"

migrate_dir=($test1)


#3.迁移备份,每两周执行一次
if [ $flag -eq 1 ];then
	for dir in ${migrate_dir[*]}
	do
		if [ -d $dir ]; then
			#构建迁移目录
			if [ ! -d $backup_dir$dir ];then
				mkdir -p $backup_dir$dir
			fi
			#文件迁移
			for file in `find $dir -type f -mtime +$keep_days -exec ls {} \;`
			do
				mv $file $backup_dir$dir
			done
		fi
	done
fi



 

Crontab每两周执行日志迁移脚本

#日志定期迁移脚本
0 4 * * 7/2 /home/wangzhengyi/scripts/clean-scripts/migrate.sh
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值