Reputation: 75
I need to get the latest file from the SFTP to my local machine. I have a concept which is to list the latest file of the target directory in SFTP first before getting the listed latest file.
Any command to complete this using Linux shell script?
file=$(sftp username@servername 'ls -ltr /server/path | tail -n 1')
I have used this command to list the latest file but it does not work. I also don't know about the command for getting the listed file, any idea?
Upvotes: 3
Views: 21312
Reputation: 4769
I did face a tough time achieving this. Apparently tail
is not a valid command when run over sftp
console.
And in my case, we had only the server access via SFTP and not over SSH. Hence the solution by https://stackoverflow.com/users/3422102/david-c-rankin didnt work for me as the solution works while executing commands over ssh
.
# this gives me name of the latest file on SFTP server
fileName=$(echo "ls -1rt" | sftp -oIdentityFile=<pathToKeyFile> username@sftpServer:/remoteDir | tail -1)
# this fetches the latest file from sftp server
echo "get $fileName" |sftp -oIdentityFile=<pathToKeyFile> username@sftpServer:/remoteDir
Wrap the above set of commands in a shell file and it will work smoothly for you.
Upvotes: 8
Reputation: 1
To get multiple file names, use the good old backquote:
file=`ssh username@servername 'ls -ltr /server/path' | grep "Mar 16"|awk '{print $9'}`
This is assuming that you can autologin to the remote. Post this using these file names, you can again do a sftp
Upvotes: 0
Reputation: 84561
You have your ls options
wrong, try:
file=$(ssh username@servername 'ls -1tr /server/path' | tail -n 1)
You are using the -l
(lowercase L
for long
listing) option instead of using -1
(number one) option (list one file per line
) This causes your ls
command to include the file permissions, file ownership, etc... which when used as input to scp
causes the command to fail.
Also, if you are providing a filename to scp
, you don't need the -r
(recursive) option. The following should be all you need for your scp
command. (don't forget to double-quote "$file"
to prevent word-splitting if there are spaces in the filename)
scp username@servername:/path/path/"$file" /my/home/directory
Upvotes: 1