Skip to content

Instantly share code, notes, and snippets.

@Stewie410
Last active June 23, 2020 21:00
Show Gist options
  • Select an option

  • Save Stewie410/38cee8c2fdb999a0e8d8177ba336978f to your computer and use it in GitHub Desktop.

Select an option

Save Stewie410/38cee8c2fdb999a0e8d8177ba336978f to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# ---------------------------
# -- Traps --
# ---------------------------
# Always execute "cleanup" function on exit
trap cleanup EXIT
# -------------------------------
# -- Functions --
# -------------------------------
# Cleanup Environment
cleanup() {
# Clear memory
unset source destination ownerUser ownerGroup
}
# Check Variables/Options
checkOpts() {
# Check Variables
[ -n "${source}" ] || { printErr "null" "source"; return 1; }
[ -n "${destination}" ] || { printErr "null" "destination"; return 1; }
[ -n "${ownerUser}" ] || { printErr "null" "ownerUser"; return 1; }
[ -n "${ownerGroup}" ] || { printErr "null" "ownerGroup}"; return 1; }
# Check Directories
[ -d "${source}" ] || { printErr "dir" "${source}"; return 1; }
mkdir --parents "${destination}" 2>/dev/null || { printErr "dir" "${destination}"; return 1; }
# Check Users
getent passwd "${ownerUser}" || { printErr "user" "${ownerUser}"; return 1; }
# Get Groups
getent group "${ownerGroup}" || { printErr "group" "${ownerGroup}"; return 1; }
# Return Success
return 0
}
# Print Errors :: String type, String message part
printErr() {
# Return if args not passed
[ -n "${2}" ] || return
# Determine message to print
local msg
case "${1,,}" in
null ) msg="Variable not defined";;
dir ) msg="Cannot locate or create directory";;
user ) msg="User does not exist";;
group ) msg="Group does not exist";;
* ) msg="An unexpected error occurred";;
esac
# Print Message
printf 'ERROR: %s: %s\n' "${msg}" "${2}"
}
# -------------------------------
# -- Variables --
# -------------------------------
source="/opt/test/old"
destination="/opt/test/new"
ownerUser="root"
ownerGroup="root"
# ---------------------------
# -- Run --
# ---------------------------
# Check for errors -- if any detected, abort script
checkOpts || exit 1
# Use rsync to mirror data from source to destination
rsync -auvHAX --safe-links --no-owner --no-group --remove-source-files "${source}/" "${destination}"
# Set Permissions on destination path
chmod --recursive 775 "${destination}"
chown --recursive "${ownerUser}:${ownerGroup}" "${destination}"
@Stewie410
Copy link
Author

Here's the context to this post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment