Tag Archives: syncronise

A Linux Bash script to sync the most recent version of a file on a remote host to a local host (using SFTP) and a password

This bash script will log in to a remote host using SFTP, find the most recently modified file in a directory, and download it to a specified local directory.

#!/bin/bash

datestamp=$(date +%Y-%m-%dT%H:%M:%S%z)
echo $datestamp

fileName=$(echo "ls -1rt" | sshpass -p PASSWD sftp user@host | tail -1)

echo "Latest file is: " $fileName

echo "lcd /the/local/target/directory/to/place/downloaded/file
get $fileName targetfilename.txt" | sshpass -p PASSWD sftp user@host

echo "-----"
echo ""

This script uses sshpass. Sshpass is a utility you can use to pass along a password to an ssh prompt when using a key is not feasible. It’s great for scripts. Just make sure that the script which contains your password is not world readable.

n.b. This script works on the default directory on the target machine. If you want to change directories on the remote host, you’ll need to echo a “cd /your/path/here” before the “lcd” statement.

The script was written to facilitate logging, which is why it has echo statements echoing the datestamp, filename of the file which is being retrieved, and separator markers.


  • You’ll need to update the script to replace user@host with the username and hostname of the user which has SFTP access to the remote host.
  • You’ll need to update PASSWD with the cleartext password of the above user.
  • Replace targetfilename.txt with the filename you want the downloaded file to have after you’ve downloaded a copy. If you want the same filename (no name change), then remove targetfilename.txt altogether.
  • And finally, replace ‘/the/local/target/directory/to/place/downloaded/file‘ with your target directory for where to download the file locally.

Set the script to run via cron at the appropriate times. Pipe the output using &>> to append all output (standard out and err) to the log file. e.g.

/usr/local/sbin/syncscript.sh &>> /var/log/syncscript.log