`rsync` is a fast and versatile utility that provides fast, incremental file transfer. Running `rsync` with a bash script can assist in carrying out routine backup and synchronization tasks. The script calls the `rsync` command telling it what to sync, and where. It’s a simple process, and I am going to explain it to you. Please remember that the `rsync` command must be installed on both the source and the destination machine.
Firstly, you need to identify the source and destination directories for the sync. For example, if you want to sync the directory `/var/www/html` from the local machine to a remote server `192.168.1.101` under `/backup/` directory, the `rsync` command would look like this:
```
rsync -avz /var/www/html/ root@192.168.1.101:/backup/
```
The options `-avz` stands for:
- `a` — archive mode
- `v` — increase verbosity
- `z` — compress file data
Now to run this command from a bash script is straightforward. Open a new file and name it as `backup.sh`:
```
#!/bin/bash
rsync -avz /var/www/html/ root@192.168.1.101:/backup/
```
Ensure you make the bash script executable by running the command:
```
chmod +x backup.sh
```
Now, you can run your bash script using:
```
./backup.sh
```
It is important to note that if you want to run `rsync` without being prompted for a password, you can use SSH passwordless login with `ssh-keygen`. Just ensure `ssh-keygen` is setup correctly on both the local and remote server. Then, you can use the `-e` ssh option with `rsync`:
```
rsync -avz -e ssh /var/www/html/ root@192.168.1.101:/backup/
```
You can also use cron to schedule your bash script to run at specific times. For instance, if you want to run your script every day at 3 am, you could add the following line to your crontab (use `crontab -e` to edit your crontab):
```
0 3 * * * /path/to/your/backup.sh
```
Keep in mind, running scripts and commands as root is not often recommended, and you should always ensure you understand a script before running it. The above is a basic example and real-world scripts can get much more complex as per the requirements.
Sources:
- The `rsync` man page: https://linux.die.net/man/1/rsync
- `rsync` over SSH: https://www.tecmint.com/rsync-over-ssh-without-password/
- Cron scheduling: https://www.ostechnix.com/a-beginners-guide-to-cron-jobs/