Skip to content

Instantly share code, notes, and snippets.

@nhamilakis
Last active April 2, 2026 11:47
Show Gist options
  • Select an option

  • Save nhamilakis/705365c5ad97e81d3aeb2db6fc85e08c to your computer and use it in GitHub Desktop.

Select an option

Save nhamilakis/705365c5ad97e81d3aeb2db6fc85e08c to your computer and use it in GitHub Desktop.
Rsync magic folder used for backup
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
import subprocess
import sys
from pathlib import Path
# ── Configuration ─────────────────────────────────────────────────────────────
LOCAL_FOLDER = Path("~/backup-magic").expanduser()
# Alias from ~/.ssh/config — user, key, port, etc. are all read from there
REMOTE_HOST = "mycluster"
REMOTE_PATH = "/data/backups/myuser"
# ── Sync ──────────────────────────────────────────────────────────────────────
def main() -> None:
if not LOCAL_FOLDER.exists():
print(f"Creating local folder: {LOCAL_FOLDER}")
LOCAL_FOLDER.mkdir(parents=True)
remote_dest = f"{REMOTE_HOST}:{REMOTE_PATH}/"
cmd = [
"rsync",
"--archive", # preserves permissions, timestamps, symlinks
"--compress", # compress during transfer
"--human-readable",
"--progress",
"--delete", # remove files on remote that were deleted locally
"--rsh=ssh -o StrictHostKeyChecking=accept-new",
f"{LOCAL_FOLDER}/", # trailing slash = sync contents, not the folder itself
remote_dest,
]
print(f"Syncing {LOCAL_FOLDER}{remote_dest}")
print()
result = subprocess.run(cmd)
if result.returncode == 0:
print("\nDone.")
else:
print(f"\nrsync exited with code {result.returncode}.", file=sys.stderr)
sys.exit(result.returncode)
if __name__ == "__main__":
main()
#!/usr/bin/env bash
LOCAL_FOLDER="$HOME/backup-magic"
REMOTE_HOST="mycluster"
REMOTE_PATH="/data/backups/myuser"
# ── Sync ──────────────────────────────────────────────────────────────────────
if [[ ! -d "$LOCAL_FOLDER" ]]; then
echo "ERROR: Local folder does not exist : $LOCAL_FOLDER"
exit 1
fi
echo "Syncing $LOCAL_FOLDER$REMOTE_HOST:$REMOTE_PATH"
echo
rsync -azhP "$LOCAL_FOLDER/" "$REMOTE_HOST:$REMOTE_PATH/"
echo "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment