Shell脚本
2020年9月10日大约 2 分钟
Shell脚本
文件清理
有的时候我们可能需要批量清理掉系统中一些文件,为了在不通过实现相关批量删除功能的方式下快速清理文件,我们可以使用shell脚本
首先我们需要将文件的路径按一定格式收集起来,比如单个路径占一行
以data.txt为例,这里每一个文件路径的相对路径单独一行,也可以是绝对路径
# data.txt
pdf/003300774001.pdf
pdf/003300774002.pdf
pdf/003300774003.pdf创建一个file-clean.sh的文件清理脚本
#!/bin/bash
echo "使用txt文件存放需要删除的文件路径(每行存放一个路径)"
root_path=""
read -e -p "是否需要定义根路径(y/n):" is_need_root
if [ ${is_need_root} = "y" ]; then
	read -e -p "请您输入文件的根路径:" input_root_path
	root_path="${input_root_path}/"
	echo "您输入文件的根路径是${input_root_path}"
elif [ ${is_need_root} = "n" ]; then
	echo "选择不设置根路径"
else
	echo "输入无效内容"
	exit
fi
current_file_name="data.txt"
read -e -p "请您输入文件名称:" file_name
if [ $file_name ]; then
    current_file_name=$file_name
fi
echo "开始清理文件"
cat $current_file_name | while read file_path; do
     if [ ! $file_path ];then
        echo "文件路径为空,跳出循环"
        continue
     fi   
	current_path="${root_path}${file_path}"
	# -f用来判断${current_path}是否为一个文件
	if [ -f ${current_path} ]; then
        #rm -rf ${current_path}
        echo "文件已删除: ${current_path}"
	else
		echo "文件不存在: ${current_path}"
	fi
done
echo "开始清理文件结束"进入输入文件清理脚本所在位置输入.file-clean.sh执行脚本
清理target
避免长期不使用的文件占用磁盘空间,清理Maven项目产生的target文件
#!/bin/bash
# 遍历所有子文件夹,寻找包含 pom.xml 的文件夹
find . -type f -name 'pom.xml' | while read -r file; do
    # 获取文件所在的目录
    dir=$(dirname "$file")
    
    # 进入该目录并运行 maven clean
    echo "Cleaning target directory in $dir"
    # (cd "$dir" && mvn clean)
    (cd "$dir" && rm -rf target)
done设置执行权限chmod +x clean_projects.sh
