This post provides a simple Bash script to automate file transfers between two machines using SFTP. The script first deletes old files from the remote machine and then transfers new files from the source machine to the remote machine.
To automate the process, SSH key-based authentication must be set up. If you’re unfamiliar with setting up SSH key-based authentication, refer to the details provided in this post.
Steps to Use the Script:
- Save the following script in a file on the source machine, e.g., sftp_transfer.sh.
#!/bin/bash
# Define variables
SFTP_USER="user_name"
SFTP_HOST="ip_address"
SFTP_PORT="port_number"
LOCAL_FILE="/backup/*" # replace it with your local file(s)
REMOTE_PATH="remote_folder_name/" # replace it with your remote folder name
# cleanup remote directory
ssh -p $SFTP_PORT $SFTP_USER@$SFTP_HOST "rm -rf $REMOTE_PATH*"
# SFTP command
sftp -oPort=$SFTP_PORT $SFTP_USER@$SFTP_HOST <<EOF
put $LOCAL_FILE $REMOTE_PATH
bye
EOF
- Make the script executable by running the following command:
chmod +x sftp_transfer.sh
- Execute the script using the following command:
bash sftp_transfer.sh
This script is ideal for automating regular file transfers, assuming SSH keys are properly configured for password-less access. Please let us know in the comments if you need further information or get any error.