Copying latest file from remote server

file-copyfilesscp

There is a collection of .doc files, in addition to other types of files, on a remote server (which supports SCP).

I am trying to write a script to retrieve the latest (most recently modified) .doc file from the remote server. The path to my current working directory cannot be absolute since my script may be deployed in another server.

I am able to solve the problem partially in two steps:

  1. Copy all the .doc files from the remote server to my local ~/Downloads folder:

    scp -i key.pem abc@xyz:/tmp/*.doc ~/Downloads/
    
  2. Select the latest file from ~/Downloads and copy it to the required folder:

    cd ~/Downloads
    latest_file=$(ls -t *.doc | head -n 1)
    cp -p "$latest_file" /current working directory
    

How can I copy the latest .doc file present in the remote server xyz under the folder /tmp to my local machine in a single statement without downloading all of them into an intermediate folder?

Best Answer

I am not really clear what your problem is, but if you're trying to copy to the current directory then just use . to refer to the current directory so that your command is:

scp -i key.pem abc@xyz:/tmp/*.doc .
Related Question