How to sync files between laptop and Raspberry Pi

Subscribe Send me a message home page tags


#raspberry-pi  #python  #turtlebot3 

In this post, we will describe how we can set up our development environment when working with Raspberry Pi. The objective is to automatically sync files between laptop and Raspberry Pi. There are three steps to achieve this goal:

Ssh Connection

To set up the ssh connection, we will use ssh-keygen

$ ssh-keygen
$ Enter passphrase (empty for no passphrase):
$ Enter same passphrase again:

The public key will be generated and stored in

~/.ssh/id_rsa.pub

Then we need to copy the public key to the remote host

ssh-copy-id -i ~/.ssh/id_rsa.pub <user>@<raspberry-pi-ip-address>

At this point, if we connect to raspberry Pi, we don't need to enter the password of the user but we still need to enter the passphrase. To avoid repeatedly entering the passphrase, we can call

ssh-add

Now we should be all set with the ssh connection.

Sync between Local Directory and Remote Directory

Suppose ~/workspace/project-raspberry-pi is the root directory of our local development workspace and the script will be deployed to ~/workspace/robot-control directory on the Raspberry Pi. To sync these two directories, we can use the command below:

rsync -r --delete ~/workspace/project-raspberry-pi/ <user>@<raspberry-pi-ip-address>:~/workspace/robot-control;

-r indicates we want to sync the directory recursively and --delete means if a file exists in the remote directory but not in the local directory, it will be deleted from the remote directory. Note that rsync command works in one direction, the first directory in the arguments is the "main" directory (e.g. in our case it's the local directory) and changes in the second directory do not have any impact on the "main" directory.

Monitor Directory

What we want is to use the rsync command whenever there is a change in the local directory. We can use the fswatch tool described in this post if we use a Macbook. Similar tools exist on other systems.

Put Everything Together

We can use the following script to automatically sync between the local directory on the laptop and the remote directory on Raspberry Pi.

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash

directoryToMonitor="~/workspace/project-raspberry-pi";

echo "start monitoring path: ${directoryToMonitor}.";

fswatch ${directoryToMonitor} | while read change;

do
    echo -e "\n[$(date)] ${change}";
    rsync -r --delete ~/workspace/project-raspberry-pi/ <user>@<raspberry-pi-ip-address>:~/workspace/robot-control;
done

----- END -----

If you have questions about this post, you could find me on Discord.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png