Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

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
share|improve this answer
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. – ioSamurai May 11 '12 at 1:36
@Ryan Mounting only relies on having FTP access. FUSE is only a problem if your local machine is restricted. – Gilles May 11 '12 at 1:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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