Skip to content

Instantly share code, notes, and snippets.

@JasonkayZK
Created July 21, 2025 02:15
Show Gist options
  • Save JasonkayZK/6847064a739bd08232e2da938d5e34ef to your computer and use it in GitHub Desktop.
Save JasonkayZK/6847064a739bd08232e2da938d5e34ef to your computer and use it in GitHub Desktop.
Sync files between servers.
#!/bin/bash
# Dependency:
# 1. rsync: yum/apt install -y rsync
# 2. password-less SSH login
#
# 0. Define server list
servers=("server-1" "server-2" "server-3")
# 1. check param num
if [ $# -lt 1 ]; then
echo "Not Enough Arguement!"
exit 1
fi
# 2. traverse all machines
for host in "${servers[@]}"; do
echo "==================== $host ===================="
# 3. traverse dir for each file
for file in "$@"; do
# 4. check file exist
if [ -e "$file" ]; then
# 5. get parent dir
pdir=$(cd -P "$(dirname "$file")" && pwd)
# 6. get file name
fname=$(basename "$file")
ssh "$host" "mkdir -p $pdir"
rsync -av "$pdir/$fname" "$host:$pdir"
else
echo "$file does not exist!"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment