When using rsync over SSH to download files from a remote server that is running out of space, it’s a good idea to delete the files on the remote side only after you have confirmed they were successfully transferred. Here are some safe ways to do that:
1. Use --remove-source-files option in rsync
rsync has a built-in option to delete source files after they have been successfully copied:
rsync -av --remove-source-files -e ssh user@remote:/path/to/files/ /local/path/
-a = archive mode (preserves permissions, timestamps, etc.)
-v = verbose
--remove-source-files = deletes the source files only if they were successfully transferred
-e ssh = use SSH for transport
Note: This deletes only regular files, not directories. You may need to clean up empty directories separately.
2. Use rsync + remote find to delete empty directories
After running the above command, you can remove empty directories on the remote side with:
ssh user@remote 'find /path/to/files -type d -empty -delete'
This safely deletes only empty directories, so you don’t accidentally remove directories that still contain files.
3. Two-step approach: rsync then remote delete
If you want more control, do it in two steps:
- Download files:
rsync -av -e ssh user@remote:/path/to/files/ /local/path/
- Verify files locally (optional):
Check that files are complete, e.g., by comparing checksums or file sizes.
- Delete files remotely:
ssh user@remote 'rm -v /path/to/files/*'
Or, if you want to be safer, delete only files that exist locally:
rsync --dry-run --out-format="%n" -av -e ssh user@remote:/path/to/files/ /local/path/ | \
xargs -I{} ssh user@remote rm -v "/path/to/files/{}"
4. Use --delete-after with rsync (for mirroring)
If you want to mirror a directory and delete remote files that no longer exist locally, you can use:
rsync -av --delete-after -e ssh user@remote:/path/to/files/ /local/path/
But be careful: this deletes files on the remote side that are not present locally, so it’s more for mirroring than for one-time cleanup.
Summary
- Safest and easiest:
rsync --remove-source-files
- Clean up empty dirs:
ssh remote 'find ... -empty -delete'
- Two-step for more control: rsync then manual remote delete
- Always verify files locally before deleting remotely if data is critical.
If you want, I can help you write a full script for your specific use case! Just let me know.