Skip to content

Instantly share code, notes, and snippets.

@ConnerWill
Last active March 6, 2023 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ConnerWill/122d457c063a021159ffbb082ccf1e47 to your computer and use it in GitHub Desktop.
Save ConnerWill/122d457c063a021159ffbb082ccf1e47 to your computer and use it in GitHub Desktop.
bash function to backup a remote server with rsync
#!/bin/env bash
###
#
# Here's what the function does:
#
# Defines variables for the remote server's username, hostname, directory to be backed up, and the local directory where the backup will be stored.
#
# It also defines a variable for the path to a file containing any files or directories to be excluded from the backup.
#
# Creates the backup directory if it doesn't exist using the mkdir -p command.
#
# Runs the rsync command to backup the remote directory to the local directory.
#
# -a option preserves the permissions and other metadata of the files being backed up,
# -v provides verbose output,
# -z compresses the data during transfer,
# --delete removes any files from the backup directory that no longer exist on the remote server,
# --exclude-from specifies the file containing any files or directories to be excluded from the backup.
# --progress option shows a progress bar for the transfer,
# --human-readable option makes the output easier to read by showing file sizes in a human-readable format.
# --rsh='ssh' option specifies that the ssh command should be used to establish the connection to the remote server.
#
###
function rsync_backup_with_progress {
# Localize variables
local SRC_USER SRC_HOST SRC_DIR DEST_DIR EXCLUDE_FILE
# Define variables
SRC_USER="remote_username"
SRC_HOST="remote_hostname"
SRC_DIR="/path/to/remote/directory"
DEST_DIR="/path/to/local/directory"
EXCLUDE_FILE="/path/to/exclude/file"
# Create backup directory if it doesn't exist
mkdir -p $DEST_DIR
# Run rsync command with progress bar
rsync -avz \
--delete \
--exclude-from=${EXCLUDE_FILE} \
--progress \
--human-readable \
--rsh='ssh' \
${SRC_USER}@${SRC_HOST}:${SRC_DIR} ${DEST_DIR}
}
rsync_backup_with_progress
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment