您的位置:首页 > 运维架构 > Linux

项目总结-Linux下批量删除无用文件

2017-06-13 09:51 411 查看

背景

有一个功能,需要定期清理指定文件夹下指定日期的无用文件,文件的存储格式是目录/yyyyMMddHH/xx.txt,文件夹以小时命名的,现在要定期删除某些日期的文件。用java调用Shell命令的rm -rf 目录/日期*的方式总数不成功,初步判断正则表达式没有匹配成功,所以没有执行删除操作。

解决办法

编写一个Shell脚本文件来删除,参数传递需要删除的日期列表,然后循环拼接删除命令完成操作,如下Shell文件命名为rmfile.sh。

#!/bin/sh

basePath=$1
dates=$2
date=${dates//,/ }
for element in $date
do
echo $basePath*/$element*
rm -rf $basePath*/$element*
done


例如:用Java的Process调用该Shell脚本文件,传递参数,示例代码:

rmfile.sh /mydata/ 20170613,20170614

之所以想起总结这个简单问题,是因为早上看到了一篇介绍Shell的循环结构的文章,刚刚想起这个简单脚本中用到了for循环,也是巩固学习的过程。

补充

Java调用Shell文件的简单方法代码如下:

public static List<String> executeShell(String shpath, String var){
String shellVar = (var==null)?"":var;
String command1 = "chmod 777 " + shpath; // 为 sh 添加权限
String command2 = "/bin/sh " + shpath + " " + shellVar;
log.debug("执行shell脚本开始:"+command2);
List<String> strList = new ArrayList<String>();
Process process = null;
BufferedReader in = null;
try {
process = Runtime.getRuntime().exec(command1); // 执行添加权限的命令
process.waitFor(); // 如果执行多个命令,必须加上
process = Runtime.getRuntime().exec(command2);
process.waitFor();

in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String str = null;
while ((str = in.readLine()) != null) {
strList.add(str);
}
} catch (IOException e) {
} catch (InterruptedException e) {
}finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
}
}
if(process != null){
process.destroy();
}
}
return strList;
}


说明:如果需要同步等待Shell文件的执行结果必须有process.waitFor(); 这个操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell java