To achieve your goal of deleting files from the remote server after they've been successfully downloaded using rsync over SSH, you have a few options. It's crucial to proceed with caution to avoid data loss. Here are some methods:
1. Using --remove-source-files
The --remove-source-files option with rsync can delete files from the source (remote server in your case) after they've been transferred successfully. This option is straightforward but requires you to be very sure about the transfer before running it, as it will permanently delete files.
rsync --remove-source-files -avz -e ssh user@remote:/path/to/files/ /local/download/path/
-a preserves file permissions, ownership, timestamps, and recursive directory transfers.
-v increases verbosity, useful for monitoring the process.
-z enables compression during the transfer.
2. Using --delete with Caution
If you're mirroring directories and want to keep them in sync, --delete can remove extraneous files from the destination. However, when used with rsync over SSH, you need to be cautious as it will delete files in the destination that don't exist in the source. Do not use this option if you're transferring files from the remote to your local machine, as it will delete files on your local machine.
However, if you're managing a two-way sync or pushing files to the remote and want to clean up, it could be considered:
rsync -avz -e ssh --delete /local/download/path/ user@remote:/path/to/files/
3. Manual Removal with find and rsync
For more control, you could first perform the rsync and then manually remove files from the remote server if they were successfully transferred. This approach requires two steps and some way to verify the transfer.
- Perform the
rsync transfer.
- Use
find and ssh to remove files:
find /local/download/path/ -type f -printf '%f\n' | ssh user@remote "cd /path/to/files/; xargs rm"
This method assumes that file names are unique and that you're transferring files (not directories) or you'll need to adjust it. This approach is less atomic than --remove-source-files and requires verification that the files were transferred correctly before running it.
Safety Considerations
- Backup: Before initiating any file deletion process, ensure you have backups of your remote files.
- Dry Run: Use
rsync with -v and -n (dry-run) to test commands without making changes.
- Logging: Consider logging the process to monitor and verify file transfers and deletions.
Each method has its use cases. --remove-source-files is simple and effective for one-way transfers where you want to clean up the source after a successful transfer. Always exercise caution and test commands in a non-critical environment first.