Shell脚本查找X天或者更旧的文件并删除

时间:2020-03-05 15:31:46  来源:igfitidea点击:

对管理员有用,如果需要,可以快速找到旧文件并删除所需的文件。
该Shell脚本将查找X天之前的文件,然后确认用户将其删除。

该脚本将以交互方式询问用户,然后再删除较旧的文件或者目录。

Shell脚本可在X天之内删除文件

#!/bin/bash
#we check for parameters
#Directory is required parameter, to avoid deleting from any other folders
if [ $# -eq 0 ]; then
echo "`basename 
Server1:~/$./delete_xdays.sh /home/yevhen/Downloads 7
Delete folder /home/yevhen/Downloads/CENTOS and all subfolders? [y/n]n
Delete folder /home/yevhen/Downloads/TFTP and all subfolders? [y/n]y
Delete file /home/yevhen/Downloads/Oracle_Solaris_Studio.certificate.pem? [y/n]^C
` " echo "Script will delete file folders older than inside " echo "If no days inputed, will use 7 days as default" fi #We save variables DIR= #check if user input days if [ x"" = "x" ]; then #if user didn't input days, we will use default value DAYS="7" else DAYS="" fi #this will create list of folders older that X days. We use command find to find them, and set maxdepth # to 1, we don't need recursively find all folders dirlist=`find $DIR -maxdepth 1 -type d -mtime +$DAYS` #now we will process each folder for dir in ${dirlist} do #this will check if user have read and write permissions if [ ! -r ${dir} -o ! -w ${dir} ]; then #if no permissions just warn, without try to delete echo "Access denied to folder ${dir}" else #if we have permissions – we ask user if really delete read -p "Delete folder ${dir} and all subfolders? [y/n]" confirm #check if user confirm deleting if [ "$confirm" = "y" ]; then #if user confirm – rm command to delete rm -rf ${dir} fi fi done #same as with directories we do with files #we get list filelist=`find $DIR -maxdepth 1 -type f -mtime +$DAYS` #proceed with every file for file in ${filelist} do #we check permissions if [ ! -r "${file}" -o ! -w "${file}" ]; then echo "Access denied to file ${file}" else #if we have permissions we ask about confirmation read -p "Delete file ${file}? [y/n]" confirm if [ "$confirm" = "y" ]; then #if confirmed – we delete file. rm -rf ${file} fi fi done

在以下脚本中,我们将删除7天前的文件和目录:

Server1:~/$./delete_xdays.sh /home/yevhen/Downloads 7
Delete folder /home/yevhen/Downloads/CENTOS and all subfolders? [y/n]n
Delete file /home/yevhen/Downloads/Oracle_Solaris_Studio.certificate.pem? [y/n]n
Delete file /home/yevhen/Downloads/sol-11_1-text-x86.iso? [y/n]^C
##代码##