Installing and using rsync on Linux

rsync (Remote Synchronization) – a program that synchronizes files and directories.

Example setup command for CentOS:

sudo yum -y install rsync

For Debian/Ubuntu:

sudo aptitude install rsync
sudo apt install rsync

I will give an example of local synchronization:

sudo rsync -avh --delete /var/www/ /root/backup/www/

Synchronizing data to a remote server:

sudo rsync -avh --delete /var/www/ root@

Synchronizing data to a local server from a remote:

sudo rsync -avh root@ /root/backup/www/

Via SSH with a non-standard port:

sudo rsync -avh -e "ssh -p 1111" root@ /root/backup/www/

To exclude any subdirectories, for example, if we synchronize /var/www/ and want to exclude /var/www/dir/ and /var/www/dir/tmp/, then we can add to the command:

--exclude='dir/' --exclude='dir/tmp/'

File exclusions by mask, for example, etc .:


To move files from a remote server to a local one:

sudo rsync -avh --remove-source-files root@ /var/www/

An example of copying MySQL data to another disk:

rsync -vrplogDtH –progress /var/lib/mysql/ /newhdd/var/lib/mysql/

I’ll give an example of my backup script (the last line deletes directories older than 30 days):

mkdir /root/backup/`date +%Y-%m-%d`
cd /root/backup/`date +%Y-%m-%d`
sudo rsync -avh -e "ssh -p 1111" --log-file=/root/backup/`date +%Y-%m-%d`/rsync.log root@* /root/backup/`date +%Y-%m-%d`/
find /root/backup -type d -mtime +30 | xargs rm -f -r

The built-in help can be obtained with the command:

man rsync

In the /etc/default/rsync file, you can configure rsync to run as a daemon.
When synchronizing with other servers, rsync must also be installed on them, or SSH must be specified.

I will describe the possible launch options:
-v (–verbose verbose)
-r (–recursive, copy data recursively)
-R (–relative, use relative paths when creating symbolic links)
-a (–archive, archiving mode, copy data recursively with preservation of symlinks, access rights and other information)
-b (–backup, backup, see optionally –backup-dir=DIR and –suffix=SUFFIX)
-c (–checksum, reconciliation by checksums, not by change time and size)
–delete (delete files)
-f (–filter = RULE, creating a filter rule)
-h (–human-readable, output in human-readable format, see also –progress)
-H (–hard-links, storing hard links)
-n (–dry-run, trial mode without any changes)
-p (–perms, save rights)
-z (–compress, data compression during transmission, see also –compress-level=NUM ​​and –skip-compress = LIST)
-x (–one-file-system, do not go beyond the current mount point)
-q (–quiet short mode)
-W (–whole-file, full copy instead of copying changed data)

How to configure SSH connection without entering a password, see my article:
Connect to SSH using the keys

If there are problems connecting via SSH using the key, then in a pinch you can specify the password manually, for example using sshpass:

apt install sshpass
sshpass -p "password" rsync ...

Leave a comment

Leave a Reply