1

I am trying to write a script that will use CURL to FTP to a folder on a file server, then count the files in that folder. If there are more than 5 files, delete the oldest one.

I know how to delete files over FTP with CURL, however the counting and getting oldest file name is where I am lost.

1

I don't think you can do this through curl. You would need to run curl -l to list the directory contents, count the matches, sort by date, and issue remote rm commands with curl -Q.

If your system supports FUSE (most do), I recommend to mount the remote directory as a filesystem. This approach lets you split your problem into two separate tasks: access the remote files by mounting them, and work on them as you would on local files. You can use curlftpfs for the remote mounting.

mkdir ftp.example.com
curlftpfs ftp.example.com ftp.example.com
cp -p /path/to/local/file ftp.example.com/remote/dir/

Now, to find the oldest files in a directory, the easiest way is to use zsh and its glob qualifiers. Working in the directory ftp.example.com/remote/dir/:

files=(*(mm))                # Om = sort by date, youngest first
if ((${#files} > 5)); then
  rm $files[-1]              # remove the last file
  # rm $files[6,-1]          # remove all but the 5 youngest files
fi
  • Hmm I am not sure if the mounting option would work as it is a GoDaddy basic web hosting package with FTP that I am sending files to. – MetaGuru May 11 '12 at 1:36
  • 1
    @Ryan Mounting only relies on having FTP access. FUSE is only a problem if your local machine is restricted. – Gilles 'SO- stop being evil' May 11 '12 at 1:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.