2

I'm creating a script based on this one. But when i run it on the results it's deleting files newer than tha date if the months aren't the same.

Linux shell script for delete old files from ftp

"Removing 02-02-2015" which is a backup i created today

#!/bin/bash
# get a list of directories and dates from ftp and remove directories older than ndays
ftpsite="hostname"
ftpuser="user"
ftppass="pass"
putdir="/full"

ndays=15


# 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 -p $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 -p $ftpsite <<EOMYF2
      user $ftpuser $ftppass
      binary
      cd $putdir
      mdelete ${lista[`expr $FNO+8`]}/*
      rmdir ${lista[`expr $FNO+8`]}
      quit
      EOMYF2
   fi
  fi
done

result => removing files older than Jan 18 Removing 02-02-2015

Community
  • 1
  • 1

1 Answers1

3

This line seems to be wrong, because it's always true:

if [ ${lista[`expr $FNO+5`]}=$MM ];

You should write spaces around "=". The correct form is:

if [ ${lista[`expr $FNO+5`]} = $MM ];

[ ] is bash builtin, and its argument will be passed to "test" command. [ asd = "$qwe" ] is equivalent to: test "asd" "=" "$qwe"

szkj
  • 733
  • 4
  • 14
  • thank you, i also got the result by doing `if [ "${lista[`expr $FNO+5`]}" = "$MM" ];` i would vote your answer up but don't have any reputation to do it :) – Aurelian Pop Feb 02 '15 at 14:54