且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用于从 ftp 删除旧文件的 Linux shell 脚本

更新时间:2023-12-04 20:40:10

这是我编写的一个脚本,用于删除远程 ftp 站点上超过 7 天的所有文件.它的工作原理是检索目录列表,解析修改日期,然后重新连接以删除任何早于 ndays 的文件.

This is a script I wrote to remove any files on a remote ftp site older than 7 days. It works by retrieving a listing of the directory, parsing the modified date, and then re-connecting to delete any files older than ndays.

我怀疑硬编码到循环中的数字(元素日期)可能会根据您的系统设置而改变.ls 命令的返回格式取决于本地系统设置.

I suspect that the numbers hard-coded into the loop (element date) may change depending on the setup of your system. The return formatting of the ls command is dependent on the local system settings.

假设您每天都进行备份,那么将 ndays 设置为 10 可能会解决您的问题.

Assuming your backups are every day, then setting ndays to 10 might solve your problem.

#!/bin/bash
# get a list of files and dates from ftp and remove files older than ndays
ftpsite="ftp.yourserver.com"
ftpuser="loginusername"
ftppass="password"
putdir="/public_ftp/admin/logs"

ndays=7


# work out our cutoff date
MM=`date --date="$ndays days ago" +%b`
DD=`date --date="$ndays days ago" +%d`


echo removing files older than $MM $DD

# get directory listing from remote source
listing=`ftp -i -n $ftpsite <<EOMYF 
user $ftpuser $ftppass
binary
cd $putdir
ls
quit
EOMYF
`
lista=( $listing )

# loop over our files
for ((FNO=0; FNO<${#lista[@]}; FNO+=9));do
  # month (element 5), day (element 6) and filename (element 8)
  #echo Date ${lista[`expr $FNO+5`]} ${lista[`expr $FNO+6`]}          File: ${lista[`expr $FNO+8`]}

  # check the date stamp
  if [ ${lista[`expr $FNO+5`]}=$MM ];
  then
    if [[ ${lista[`expr $FNO+6`]} -lt $DD ]];
    then
      # Remove this file
      echo "Removing ${lista[`expr $FNO+8`]}"
      ftp -i -n $ftpsite <<EOMYF2 
      user $ftpuser $ftppass
      binary
      cd $putdir
      delete ${lista[`expr $FNO+8`]}
      quit
EOMYF2


    fi
  fi
done