Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have this folder full of files.

Once per day, I want the newest of the files to be FTPed automatically to a file server.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Make a short script, get the filename via this line:

newestfilename=`ls -t $dir| head -1`

(assuming $dir is the directory you're interested in), then feed $filename to your FTP command, and of course, cron this script to run once a day.

If you have ncftp, you can use the following command to ftp the file:

ncftpput -Uftpuser -Pftppasswd ftphost /remote/path $dir/$newestfilename

Without ncftp, this may work:

ftp -u ftp://username:passwd@ftp.example.com/path/to/remote_file $dir/$newestfilename
share|improve this answer
    
Quick question, if I change 'head -1' to 'head -2' will that get the second to newest file? I just want to make sure I don't grab a file that is mid-write. –  ioSamurai May 10 '12 at 17:52
    
No if you want the second file, you'd replace head -1 with head -2 | tail -1 :) –  Ansari May 10 '12 at 18:27
1  
It worth note, that piping ls is not good in case filename contains smthing exotic, ex, '\n`. –  KAction Oct 30 '12 at 4:56

Locating the newest file

The easiest way to find the newest file in a directory is to use zsh and its glob qualifiers om to sort by modification time and [1] to pick the most recent match.

upload /path/to/dir/*(om[1])

There's no good, portable method. The only portable method is to use ls -t to list files by date and parse the result, but parsing ls is fraught with dangers. Do this only if you're sure that your file names contain no newlines or non-printable characters.

upload "$(ls -t /path/to/dir | head -n 1)"

FTP upload

For the upload, there are many tools. A commonly installed one is curl.

curl -T /path/to/local/file ftp://ftp.example.com/remote/dir

Another approach is to mount the remote directory as a filesystem, for example with curlftpfs.

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

Automating the task

Add a crontab entry to perform the task every day. Run crontab -e and add a line like this:

SHELL=/bin/zsh
42 3 * * * curl -T /path/to/dir/*(om[1]) ftp://ftp.example.com/remote/dir
share|improve this answer

Your Answer

 
discard

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.