Gabriel Syme
Gabriel Syme

Reputation: 445

Scp the Three Newest Files Using Bash

I'm trying to scp the three newest files in a directory. Right now I use ls -t | head -3 to find out their names and just write them out in the scp command, but this becomes arduous. I tried using ls -t | head -3 | scp *username*@*address*:*path* but this didn't work. What would be the best way to do this?

Upvotes: 4

Views: 3688

Answers (4)

ltc
ltc

Reputation: 3361

perhaps the simplest solution, but it does not deal with spaces in filenames

scp `ls -t | head -3` user@server:.

using xargs has the advantage of dealing with spaces in file names, but will execute scp three times

ls -t | head -3 | xargs -i scp {} user@server:.

a loop based solution would look like this. We use while read here because the default delimiter for read is the newline character not the space character like the for loop

ls -t | head -3 | while read file ; do scp $file user@server ; done

saddly, the perfect solution, one which executes a single scp command while working nicely with white space, eludes me at the moment.

Upvotes: 8

fibbers
fibbers

Reputation: 137

This probably isn't relevant anymore for the poster, but you brought me to an idea which I think is what you want:

tar cf - `ls -t | head -3` | ssh *username*@*server* tar xf - -C *path*

Upvotes: 1

anubhava
anubhava

Reputation: 785008

Try this script to scp latest 3 files from supplied 1st argument path to this script:

#!/bin/bash

DIR="$1"

for f in $(ls -t `find ${DIR} -maxdepth 1 -type f` | head -3)
 do
    scp ${f} user@host:destinationDirectory
done

find -type f makes sure only files are found in ${DIR} and head -3 takes top 3 files.

Upvotes: 1

grantk
grantk

Reputation: 4058

Write a simple bash script. This one will send the last three files as long as they are a file and not a directory.

#!/bin/bash

DIR=`/bin/pwd`

for file in `ls -t ${DIR} | head -3`:
 do
  if [ -f ${file} ];
  then
    scp ${file} user@host:destinationDirectory
  fi
done

Upvotes: 1

Related Questions