Scp the Three Newest Files with Bash

I am trying to view three new files in a directory. I'm using ls -t | head -3 right now ls -t | head -3 ls -t | head -3 to find out their names and just write them in the scp command, but it gets difficult. I tried using ls -t | head -3 | scp *username*@*address*:*path* ls -t | head -3 | scp *username*@*address*:*path* ls -t | head -3 | scp *username*@*address*:*path* , but this did not work. What would be the best way to do this?

+4
source share
4 answers

perhaps the easiest solution, but it does not apply to spaces in file names

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

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

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

a loop-based solution will look like this. We use by reading here because the default delimiter for reading is a newline and not a space character like a for loop

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

saddly, an ideal solution that executes one scp command when working with white space is eluding me at the moment.

+6
source

Write a simple bash script. It will send the last three files if they are a file, 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 
+1
source

Try the script to look at the last 3 files from the provided 1st argument to the 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 ensures that only files are found in $ {DIR}, and head -3 occupies the top 3 files.

+1
source

Perhaps this is no longer relevant for the poster, but you led me to the idea that I think you need:

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

Source: https://habr.com/ru/post/1346368/


All Articles