Retrieve the last created file from a remote directory using SSH
Issue
You have files being created in a folder (logs, backup, …) on a remote Linux machine and you want to retrieve the last file that has been created on your local Linux machine.
Solution
- Copy and paste the below code in a file on your computer
- Customize the variables at the top of the file
- Make the file executable
Code
remote_host=""
remote_user="user"
remote_dir="/path/to/folder/"
local_dir="/path/to/folder/"
echo "Retrieving last filename"
last_file=$(ssh ${remote_user}@${remote_host} "ls -t ${remote_dir} | head -1")
if [ "${last_backup}" == "" ]; then
echo "ERROR: didn't find any file, cannot continue!"
else
echo "The last file is: ${last_backup}"
rsync -avzh --progress ${remote_user}@${remote_host}:${remote_dir}/${last_file} ${local_dir}
fi
Source
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.