删除旧文件,保留最新的几个文件或者文件夹
执行命令 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 删除回车符