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