shell脚本删除旧文件

删除旧文件,保留最新的几个文件或者文件夹

执行命令 sh test.sh /d/test 5

保留d盘test目录最新的5个文件或者文件夹

#!/bin/sh
#rm_file>14day

#要删除的目录
rm_file_dir=$1
echo "rm_file_dir = ${rm_file_dir}"

#保留文件数量
ReservedNum=$2
echo "ReservedNum = ${ReservedNum}"

if [ -z "$rm_file_dir" ] || [ -z "$ReservedNum" ];then
    echo "not found rm_file_dir or ReservedNum"
    exit 1
fi

cd ${rm_file_dir}
RootDir=$(cd $(dirname $0);pwd)     #当前文件路径
FileNum=$(ls -Art| wc -l)           #查找文件数量
OldFile=$(ls -Art|head -1)          #找出最久的一个文件or文件夹
echo "RootDir = ${RootDir}"
echo "rm_file_dir = ${rm_file_dir}"
echo "fileNum = ${FileNum}"
echo "OldFile = ${OldFile}"

if [ $RootDir == $rm_file_dir ];then
    echo $RootDir
    echo $rm_file_dir
    echo "FileNum:$FileNum"
    echo "ReservedNum:$ReservedNum"
    while (($FileNum>$ReservedNum))
    do
        echo "Delete File:"$RootDir'/'$OldFile
        rm -rf $RootDir'/'$OldFile
        let "FileNum--"
        OldFile=$(ls -rt|head -1)
    done
else
    echo "error file path"
fi

ps:由于windows机器和linux机器编码问题,windows脚本复制到linux机器 出现错误:

syntax error near unexpected token `$'\r''

解决方法:linux机器执行命令:sed -i 's/\r//g' test.sh 删除回车符

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值