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. W开发者_运维问答hat would be the best way to do this?
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.
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
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.
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*
精彩评论