How to automate backups in Linux with rsync and cron

Last update: 28/01/2026
Author Isaac
  • Rsync allows you to efficiently synchronize data by copying only the changes and preserving permissions, ideal for local and remote backups.
  • Combining rsync with keys SSH and scheduled tasks in cron can automate secure backups without manual intervention.
  • Advanced options such as --delete, --link-dest, --exclude, or --dry-run allow you to fine-tune full, differential, and incremental backups and minimize errors.
  • A good plan backup rsync includes restore testing, backup rotation, encryption of sensitive data, and monitoring. logs and alerts.

Automating backups with rsync on Linux

If you manage servers or work daily with LinuxSooner or later you'll have to consider it How to automate reliable backups without complicating your lifeThat's where it comes in. rsyncA veteran tool, highly polished and perfect for creating fast, incremental, and easy-to-schedule backups with cron.

In this guide you will see, in great detail and without beating around the bush, how to use rsync to make local, remote, full, differential and incremental backupsHow to automate everything with cron, how to integrate it with SSH without asking for a password, what typical errors to avoid, and what best practices will save you from surprises the day something goes wrong.

What is rsync and why is it used so much for backups?

Rsync is a command-line utility commands designed to synchronize files and directories between two locations: they can be on the same computer, on different servers, or even on different systems like Linux, Unix or macOS.

Its main advantage over simpler commands like cp o scp es que It doesn't copy everything verbatim, but only what has changed between the source and destination.To do this, it compares both sides and applies an algorithm that sends only the differences, which greatly reduces the cost. There copy and bandwidth consumed.

Furthermore, rsync understands file system metadata very wellIt can preserve permissions, owners, groups, timestamps, symbolic links, or devices, making it ideal for system-level backups and migrations between servers.

Another strong point is that works without problem over SSHinheriting the encryption and authentication of this protocol. This allows you to set up a secure remote backup system without needing to set up VPNs or additional services, simply by leveraging the SSH access you already use daily.

Installing and verifying rsync on Linux

Install rsync on Linux

In most modern distributions, rsync comes installed by defaultEven so, it's always worth checking the version and, if necessary, installing or updating the package from the official repositories.

Check if rsync is installed

In any Debian or Red Hat-based distribution, you can do something as simple as:

rsync --version

If the command returns version information, it's already available. If you see a "command not found" message or similar, You need to install it from the package manager.

Install rsync on Ubuntu, Debian and derivatives

On Ubuntu or Debian-type systems, simply:

sudo apt update
sudo apt install rsync

This will give you the version provided by your distribution, which is sufficient for Local and remote backups, and automation with cron in most scenarios.

Install rsync on Red Hat, CentOS, Rocky Linux and similar

In environments based on Red Hat, CentOS, Rocky Linux or AlmaLinux you can use:

sudo dnf install rsync

Manager It will install rsync if it's not present and check for updates if you already have it.so that you maintain a recent version at both the source and destination.

Basic syntax and most used options of rsync

The general form of the command is very straightforward, but it's worth getting the hang of the syntax to avoid confusion with the paths:

rsync ORIGEN DESTINO

To synchronize with a remote server via SSH, what changes is the notation of the destination or source path:

rsync /ruta/local usuario@servidor:/ruta/remota

Some fundamental options that you will use constantly are:

  • -a: file mode. Groups several options (-r, -l, -p, -t, -g, -o, -D) for traverse subdirectories and preserve permissions, owners, groups, times, links, and devices.
  • -vDetailed mode: Shows what is being copied. Useful for understanding what is rsync doing on each pass.
  • -z: compresses the data during transfer, which Save bandwidth on slow or congested links.
  • --progress: shows the real-time progress of the files being transferred.
  • --delete: deletes files at the destination that no longer exist at the source, keeping an exact replica.
  • --exclude: It allows exclude files or directories according to patterns, for example --exclude="*.log" o --exclude="tmp/".
  • -e ssh: specifies the remote shell, normally SSH for secure backupsIt is usually implicit when using a destination with usuario@host:but it can be stated explicitly.
  • --dry-run: simulation mode, shows what would happen without copying or deleting anything. Perfect for testing commands before launching them in real life..
  • --log-file=/ruta/log: writes the execution details to a log file for auditing or diagnostics.

First practical examples of rsync

To fully understand how rsync behaves, it's best to watch simple examples both locally and remotely and observe the effect that some key options have.

  How to get your finances back on track

Copy a directory to local

A typical example would be replicating a directory within the same server:

rsync -av /origen/ruta/ /destino/ruta/

That command will copy the contents of /origen/ruta/ a /destino/ruta/preserving metadata. Note the trailing slash of the source: indicates that you want to synchronize the directory contents and not the directory itself.

Synchronize with a remote server via SSH

If you want to send data to another server securely, simply enter the username, the server's IP address or domain, and the remote path:

rsync -avz /local/dir/ usuario@192.168.1.50:/backup/remote/dir/

The option -z adds compressionThis is very useful on slow or high-latency networks. If you already have SSH access, rsync will use it directly without any further configuration.

Test before running with –dry-run

Before using delicate options such as --deleteIt makes perfect sense to run a simulation:

rsync -avz --dry-run /local/dir/ usuario@remoto:/destino/

This way you can see which files would be copied, updated, or deleted without actually touching the data. It's a excellent safety net when you're fine-tuning your command.

Duplicate two directories 1:1

If the goal is for the destination to be an exact mirror of the source, including deletions, you can use:

rsync -av --delete /fuente/ /destino/

With this Everything that disappears from the origin will eventually be erased in the destinationIdeal for copies that aim to be a faithful replica, but it should be used with caution.

Types of copies with rsync: full, differential, and incremental

Once you've mastered the basics, it's important to understand how to model your backups. With rsync you can implement Full, differential and incremental backups without the need for additional tools, although it is useful to know about alternatives such as Resty tutorial on Linux.

Full copy using rsync

A full copy transfers all files from the source directory to the destination, including subfolders:

rsync -a /ruta/al/directorio/fuente/ /ruta/al/directorio/destino/

This is the pattern you will normally use the first time you set up a backup. From then on, subsequent runs will only copy changesbut conceptually they remain "complete" in the sense that the destination ends with a complete picture of the origin.

Differential copy with –delete

If you want the destination to accurately reflect the current state of the source, including deleted files, you can add:

rsync -a --delete /ruta/al/directorio/fuente/ /ruta/al/directorio/destino/

The option –delete keeps the destination synchronized down to the millimeter with the source. Only new or modified files will be transferred, and those that no longer exist in the source will be deleted at the destination, functioning as a continuous differential copy.

Incremental copy with –link-dest

To go one step further and save even more space, you can use incremental copies based on hard links using the option --link-dest.

The idea is this: you have a previous copy (for example, from the previous day) and you want to create a new daily "snapshot" where Only the blocks that change are physically stored, while unchanged files are represented as links to the previous copy.

A typical command would look something like this:

rsync -a --link-dest=/backups/dia-anterior/ /datos/ /backups/hoy/

In this way, in /backups/hoy/ Only new or modified data is written, and the rest of the files are links to the previous backup.
saving a lot of space without losing the feeling of having complete snapshots daily.

Configure manual backups with rsync

Beyond the concepts, it's crucial to know how to assemble real-world backup examples with specific paths, both locally and to external disks or remote servers.

Back up your personal directory

Imagine you want to make a copy of /home/usuario/ towards a mounted disk /mnt/disco_backup:

rsync -av /home/usuario/ /mnt/disco_backup/

This command It retains permissions, owners, groups, and times., and keeps the contents of the external drive synchronized with your home directory.

System configuration backup

To cover your back with server configuration, you can copy /etc/ to a local or remote route:

rsync -avz /etc/ usuario@servidor-remoto:/backup/etc/

That way you'll always have one. recent snapshot of the configuration files, very useful for quick restores or for comparing changes after an update.

Full remote backup of /home

A typical scenario on multi-user servers is to copy everything /home/ to another machine:

rsync -avz --delete /home/usuario/ usuario@servidor-remoto:/ruta/backup/

With option –delete ensures that the backup is an exact replica. Combined with -z For compression, a reasonable transfer rate is achieved even on networks that are not very fast.

Exclude unnecessary files and directories

In many projects, copying absolutely everything doesn't make sense: logs, temporary files, or downloadable dependencies are often unnecessary. For that, you can use:

rsync -av --exclude='*.tmp' --exclude='node_modules/' /proyecto/ /backup/proyecto/

Thereby You keep what's important and don't fill the disc with noise that you could easily regenerate.

Rsync over SSH without a password: preparing the environment

For an automated backup system to be truly convenient, you need to rsync can connect to the remote server without asking for a password each timeThe standard way to achieve this is by using SSH public key authentication.

Generate the SSH key pair on the source machine

On the server from which you will launch the backups, run:

  How to fix Outlook error 0x800CCC0F step by step

ssh-keygen -t ed25519

Balance Enter In all questions, use the default values. This will create a private and a public key in your folder. ~/.ssh/, that They will be used to identify you on the remote server without a password..

Copy the public key to the backup server

Once you have the key pair, all that remains is to copy the public key to the destination server:

ssh-copy-id backup@192.168.1.50

Replaces backup and the IP address for your specific username and server. After entering the password once, the key will be recorded in ~/.ssh/authorized_keys on the remote server.

Try accessing without a password

To verify that everything is working, try connecting via SSH:

ssh backup@192.168.1.50

If you log in directly without being prompted for a password, you can Use rsync non-interactively, ideal for being called from scripts and cron jobs.

Automate backups with cron and rsync

Once you have your rsync command fine-tuned and key authentication ready, the next natural step is automate executions with cron to forget about manually running backups.

Quick introduction to cron

cron It is the classic task scheduler for Unix systems. It allows you to run commands or scripts at defined intervals (every minute, every hour, daily, weekly, etc.). Each user has their own table with scheduled tasks, accessible with:

crontab -e

The entries follow this format:

MIN HORA DIA-MES MES DIA-SEMANA comando-a-ejecutar

Schedule a daily backup with rsync

Let's say you want to make a daily copy of /var/backups/ to a remote server at 2:00 in the morning:

0 2 * * * rsync -avz /var/backups/ backup@192.168.1.50:/mnt/servidor_backups/

This line in your crontab will take care of Launch the command every day at 02:00 without manual intervention, taking advantage of passwordless SSH authentication.

Use scripts for more complex tasks

As your needs grow, it may be more convenient to encapsulate the logic in a scriptInstead of putting everything into one line of the crontab. For example:

vi /usr/local/sbin/rsync_backup.sh

Within the script you could have something like:

#!/bin/bash
rsync -avz --delete /home/your_user/ backup@source.domain.com:/backups/home/ --log-file=/var/log/rsync-home.log

Then you make it executable with:

chmod +x /usr/local/sbin/rsync_backup.sh

And in the crontab you just add:

0 23 * * * /usr/local/sbin/rsync_backup.sh

Thereby You will clearly separate the backup logic from the programmingfacilitating maintenance and purification.

Rsync as a daemon: password-protected file backups

Although the rsync + SSH combination is usually the most convenient, you can also set up an rsync server as a daemon and authenticate with password files instead of SSH keys.

The typical setup would involve editing /etc/rsyncd.conf to define data modules, user, group, and read-only behavior, for example:

pid file = /var/run/rsyncd.pid
uid = backup-user
gid = backup-user
read only = yes

path = /path/to/backup
list = yes
auth users = backup-user
secrets file = /etc/rsyncd.passwd

The password file is defined in /etc/rsyncd.passwd with content like this:

backup-user:mi-pass-secreta

And it is protected with:

chmod 0600 /etc/rsyncd.passwd

On the client you can use:

rsync -a --password-file=/etc/rsyncd.passwd backup-user@source-server-ip::data /destino/path/$(date +%Y-%m-%d)/

This is how they are generated backup folders organized by date, keeping the data read-only on the source server to prevent accidental modifications.

Best practices and checklist for backups with rsync

Setting up a working backup is fine, but build one that will last for years without giving you trouble It requires following some fairly basic good practices.

What to include in your copies

When thinking about what to back up, don't limit yourself to the obvious documents. It's important to cover:

  • Critical data: databases, application directories, customer files, orders, etc.
  • System settings: /etc/, service configuration files, virtual hosts, etc.
  • Static files: images, web content, multimedia material.

Truly sensitive data is usually the mix of business data + configurationbecause they allow the work environment to be rebuilt quickly.

Backup frequency

Not all data needs to be presented at the same rate. A reasonable rule would be:

  • Highly sensitive data (production databases, billing systems): daily copies or even every few hours.
  • Data with moderate changes: daily or weekly copies depending on criticality.
  • Almost static data (archival material, old logs): less frequent backups or monthly snapshots.

Remember that rsync, when properly configured, allows fast incremental backupsSo it's better to err on the side of caution and make copies more frequently than to fall short.

Rotation and storage in multiple locations

It makes no sense to accumulate copies until the disk is full. A typical strategy involves maintain a limited number of copies (for example, the last 7 days) and delete the oldest ones as new ones are created.

It is also vital Distribute your backups across different locations: local disk, remote server, maybe some storage in the cloud. That way you don't depend on a single physical location.

Encryption and copy protection

If sensitive data is stored in backups (and this is often the case), you should consider encrypting them with tools like GPG or storing them in encrypted volumesIt's pointless to have an excellent backup policy if someone then takes a disk from the office and can read it without any problems.

Task monitoring and logging

A backup that fails silently is useless. It's important:

  • Record the executions in log files with --log-file.
  • Review the logs periodically or integrate alerts (by email, monitoring, etc.).
  • Perform restoration tests from time to time to make sure the copies are actually usable.

Common mistakes when using rsync and how to avoid them

rsync is very reliable, but there are several classic pitfalls that are worth keeping an eye on to avoid messing things up at the worst possible time.

insufficient permissions

One of the most common mistakes is that the user running rsync does not have permissions sufficient to read at the source or write at the destination. If you encounter "Permission denied", check that:

  • The user has read access to the tree you want to copy.
  • The destination route is writable by that user.
  • When necessary, use sudo on the origin/local side.

When connecting remotely, make sure the SSH user you are using is correct. It has permissions over the destination routes (and, if necessary, configure) sudo there too).

Confusions with relative and absolute paths and trailing slashes

Relative paths can create misunderstandings, especially in scripts. It's always best to use relative paths. absolute paths that begin with "/" to avoid surprises depending on the directory from which the command is executed.

Regarding the end bars, remember:

  • /origen/ → copy the contents of that directory.
  • /origen → copies the directory itself into the destination.

If you make a mistake here, it's easy to end up with strangely nested routes, so carefully review the desired behavior and lean on --dry-run to check.

Dangerous use of –delete

--delete It's an extremely powerful and useful option, but it's also where most disasters occur. Basically, it tells rsync to... Delete in the destination everything that you don't see in the originTherefore, an error in the source path can empty a good folder on the backup server.

To reduce risks:

  • Always test the command with --dry-run before removing it.
  • Double-check the origin and destination routes.
  • In highly critical environments you can choose to Do not use –delete on all passesbut only in specific tasks.

Problems with sizes and exclusions

For very large backups, it can be useful to limit what is included in the copy by size, using options such as --max-size o --min-sizeFor example, to copy only files between 10 MB and 100 MB:

rsync -av --min-size=10M --max-size=100M /origen/ /destino/

Combined with exclusion patterns, it allows you to filter dispensable files such as huge logs, caches, or temporary files, making copies and restorations easier.

Real-world use cases where rsync shines

Beyond generic examples, there are several contexts where rsync becomes almost irreplaceable due to its combination of speed, flexibility, and simplicity.

E-commerce and business applications

In online stores, ERPs or CRMs hosted on Linux servers, rsync allows back up databases (using dumps) and static files (product images, customer documents, etc.) to a backup server or another data center, minimizing the window of data loss.

Media outlets, blogs and news portals

On sites with a lot of multimedia content and a large volume of articles, rsync makes it easier to:

  • Synchronize static content directories between servers (for example, between a primary server and a backup server).
  • Copy periodically captures of databases and key files to external storage.

By transferring only what has changed, backup runs are fast, even with a large number of images or videos.

Development environments and CI/CD

In continuous integration and continuous deployment pipelines, rsync is often used for:

  • Synchronize source code and compiled artifacts towards staging or production servers.
  • Replicate directories between different nodes in a server farm.
  • Update only the modified part of an application, without having to re-upload everything in each release.

Its combination of speed, SSH support, and permission preservation makes it very user-friendly for automation with scripts and DevOps tools.

With all this in mind, rsync becomes a kind of Swiss Army knife for backing up and synchronizing files: It works equally well for a home backup of your personal folder as it does for the backup strategy of a fleet of production servers.If you combine it with SSH keys, cron, good rotation practices, regular restore testing, and some common sense when using options like --deleteYou will have a powerful, flexible and very robust backup system without the need to deploy heavy or complex solutions.

Retic tutorial on Linux
Related article:
Complete Resti tutorial for Linux for secure backups