Linux shell script for delete old files from ftp

后端 未结 5 1581
醉梦人生
醉梦人生 2021-01-02 14:21

There is a problem - need to store the database backup on the FTP. On the FTP should not be more than 10 back-ups, ie, After you add backup to FTP should be removed, the old

5条回答
  •  耶瑟儿~
    2021-01-02 14:33

    This one is dealing with sftp and has proper date check as the script from @Graeme is only working within one month:

    #!/bin/bash
    # get a list of files and dates from ftp and remove files older than ndays
    ftpsite="sftp -b-  -oIdentityFile= -oPort=  @"
    putdir="/data"
    
    ndays=19
    
    # work out our cutoff date
    MM=`date --date="$ndays days ago" +%b`
    DD=`date --date="$ndays days ago" +%d`
    TT=`date --date="$ndays days ago" +%s`
    
    echo removing files older than $MM $DD
    
    # get directory listing from remote source
    echo "
    cd $putdir
    ls -l
    "|$ftpsite >dirlist
    
    # skip first three and last line, ftp command echo
    listing="`tail -n+4 dirlist|head -n-1`"
    
    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`]}
    
      fdate="${lista[`expr $FNO+5`]} ${lista[`expr $FNO+6`]} ${lista[`expr $FNO+7`]}"
      sdate=`date --date="$fdate" +%s`
      # check the date stamp
      if [ $sdate -lt $TT ]
      then
          # Remove this file
          echo "$MM $DD: Removing  ${lista[`expr $FNO+5`]} /  ${lista[`expr $FNO+6`]} / ${lista[`expr $FNO+8`]}"
          $ftpsite <

提交回复
热议问题