#server Script to sync files and folder from source to another destination with rsync whenever any updatation in directory or file
Location could be remote for syncing you can ssh if the location is live:-
Automate the rsync
To achieve automatic synchronization whenever a file is added to the source directory, you can use `rsync` in conjunction with `inotifywait`, a Linux command-line tool that waits for changes to files or directories and then executes a command when an event occurs. Here's how you can set it up:
### 1. Install `inotify-tools`
First, ensure that `inotify-tools` is installed on your system. You can install it using your package manager. For Ubuntu, you can use:
```bash
sudo apt-get install inotify-tools
```
### 2. Create a Bash Script
Create a Bash script that listens for file changes in the source directory and triggers `rsync` when a file is added. Here's an example:
```bash
#!/bin/bash
# Source and destination directories
source_dir="/path/to/source"
destination_dir="/path/to/destination"
# Run rsync command when a file is added to the source directory
inotifywait -m -e create --format '%f' "$source_dir" | while read FILE
do
rsync -avh "$source_dir/$FILE" "$destination_dir"
done
```
Save this script in a file, for example, `sync_on_add.sh`, and make it executable:
```bash
chmod +x sync_on_add.sh
```
### 3. Run the Script
Run the script in the background:
```bash
./sync_on_add.sh &
```
### How It Works
- The script continuously monitors the source directory (`/path/to/source`) for the creation of new files (`-e create`).
- When a new file is created, `inotifywait` outputs the filename.
- The `while` loop reads the filename and triggers `rsync` to synchronize the new file to the destination directory (`/path/to/destination`).
### Notes:
- Ensure that the script is running continuously in the background to monitor changes (`&` at the end of the command).
- Adjust the source and destination directories in the script to match your setup.
- This setup will only sync files when they are added to the source directory. If you want to sync on other events (e.g., modification or deletion), you can adjust the `inotifywait` options accordingly (`-e modify`, `-e delete`, etc.).
With this setup, `rsync` will automatically synchronize files to the destination directory whenever a new file is added to the source directory.
Comments
Post a Comment