FTP Files From a Folder in the Order they Were Originally Written to Disk

So, I’ve been pretty silent on here as of late.  Well, if I’m honest, I don’t post on here very often in general.  But this time, I have an excuse.  I got a full time job.  I’ve been more focused on the backend of things these days, which is a nice change of pace from all the front-end headaches I was dealing with.  But moving on…

In the app I’m working on, I needed a way to FTP a bunch of files to my dev server from my local machine, but I needed them to be FTP’d in the order they were originally written to disk.  Why would I need to do this, you ask? Just trust me, I needed to and so do you, which is presumably why you’re here. Now, you could go write some fancy script to do this, but you really don’t need to.  The xargs command is here to save the day.  Here’s what to do:

Open a terminal on your Mac and cd to the directory containing the files you need, then enter this command:

ls -tr | xargs -I {} ftp -u ftp://username:password@yourserver.com:21/subdirectory/{} {}

Let’s break down the magic:

ls -tr

All this does is list the files in chronological order from oldest to newest.

| xargs

The output from your ls command is piped to the xargs command.  The -I {} option tells xargs that, in the command you’re about to feed it, take all occurences of {} and replace it with the output being piped from the ls -tr command.  In this case, that will just be the file name.

ftp -u ftp://username:password@yourserver.com:21/subdirectory/{} {}

This is just the command we’re feeding xargs to iteratively repeat for each line of output from ls -tr.  This is a standard one-line ftp command.  So if the output from the first iteration of ls -tr was file-1.txt, then xargs would execute:

ftp -u ftp://username:password@yourserver.com:21/subdirectory/file-1.txt file-1.txt

Get it?