sajad torkamani

It's often useful to quickly copy a file from our local machine to a remote server or from a remote server to our local machine. I find myself doing this frequently with configuration files like those of Nginx . Fortunately, the rsync tool makes this easy.

Copy files from local to remote machine

rsync -LPa <local_path> <remote_path>

Example 1: without SSH alias

rsync -LPa /tmp/foo.txt sajad@172.12.34.56:/tmp/mydir/foo.txt

This will copy the file /tmp/foo.txt on our local machine to the path /tmp/mydir/foo.txt on the remote machine with the IP address 172.12.34.56.

You must configure SSH access to the remote machine for this to work. In other words, for the above rsync command to work, you should have successfully configured SSH access so that running ssh sajad@172.12.34.56 should log you into the remote machine. Refer to this article for how to get SSH authentication to work.

Example 2: with SSH alias

Assuming we've configured an SSH alias so that prod is an alias for some username and IP address (e.g., sajad@172.12.34.56), we can further simplify the rsync command:

rsync -LPa /tmp/foo.txt prod:/tmp/mydir/foo.txt

Copy files from remote to local machine

rsync -LPa <remote_path> <local_path>

Example 1: without SSH alias

rsync -LPa sajad@172.12.34.56:/tmp/mydir/foo.txt /tmp/foo.txt 

Works the same way as copying from local to remote; we just specify the remote path first.

Example 2: with SSH alias

rsync -LPa prod:/tmp/mydir/foo.txt /tmp/foo.txt 

Rsync options

Rsync comes with many options (see man rsync) but -LPa covers most of my copying use cases as I suspect it would for most people. You can find out more details about -LPa with explainshell.

Tagged: Unix