shellsftp

Get latest file from SFTP to local machine


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?


Solution

  • 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