Skip to content

Instantly share code, notes, and snippets.

@jimdiroffii
Created August 15, 2023 01:22
Show Gist options
  • Save jimdiroffii/7b6b3e1e829b838de82320d60db8b5c2 to your computer and use it in GitHub Desktop.
Save jimdiroffii/7b6b3e1e829b838de82320d60db8b5c2 to your computer and use it in GitHub Desktop.
Backup Ubuntu Directory
backup_dir_function() {
# Log the start of the command
logger -p syslog.info "Starting backup process."
# must pass in a directory
directory="$1"
# Convert to absolute path if a relative path is given
if [[ ! "$directory" = /* ]]; then
directory="$(pwd)/$directory"
fi
if [ -d "$directory" ]; then
# get the folder name
root_folder_name=$(basename "$directory")
# get the parent directory
parent_directory=$(dirname "$directory")
# get the current date and time
timestamp=$(date +"%Y%m%d_%H%M%S")
# Define backup directory
backup_directory="/var/backups"
backup_file_name="${backup_directory}/${root_folder_name}_${timestamp}.tar.gz"
# Check and create backup directory
if [ ! -d "$backup_directory" ]; then
mkdir -p "$backup_directory"
if [ $? -ne 0 ]; then
echo "Error: Failed to create backup directory."
return 1
fi
fi
# tar command to create the backup with preserving permissions without logging every file
if sudo tar -zcpvf "$backup_file_name" -C "$parent_directory" "$root_folder_name" > /dev/null; then
echo "Backup of $directory created at [$backup_directory] with name ${root_folder_name}_${timestamp}.tar.gz"
# Log the successful completion of the command
logger -p syslog.info "Backup process completed successfully."
else
echo "Error: Backup of $directory failed."
logger -p syslog.err "Error: Backup of $directory failed."
return 1
fi
else
echo "Error: $directory is not a directory."
# Log the error
logger "Error: $directory is not a directory."
return 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment