Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scp the Three Newest Files Using Bash

Tags:

bash

scp

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?

like image 932
Gabriel Syme Avatar asked Dec 28 '22 22:12

Gabriel Syme


1 Answers

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.

like image 105
ltc Avatar answered Jan 14 '23 06:01

ltc