Skip to content

Instantly share code, notes, and snippets.

@NorbertFeria
Created August 24, 2024 08:23
Show Gist options
  • Select an option

  • Save NorbertFeria/4c407d89fe0b0e458fbbfc2aeedcf1cb to your computer and use it in GitHub Desktop.

Select an option

Save NorbertFeria/4c407d89fe0b0e458fbbfc2aeedcf1cb to your computer and use it in GitHub Desktop.
shellscript to backup an entire folder.
#!/bin/bash
# Default directories
DEFAULT_BACKUP_DIR="./backups"
DEFAULT_DIR_TO_COMPRESS="./public_html"
# Prompt for the directory to compress and backup
read -p "Enter the directory to compress [${DEFAULT_DIR_TO_COMPRESS}]: " DIR_TO_COMPRESS
DIR_TO_COMPRESS=${DIR_TO_COMPRESS:-$DEFAULT_DIR_TO_COMPRESS}
# Prompt for backup directory
read -p "Enter the backup directory [${DEFAULT_BACKUP_DIR}]: " BACKUP_DIR
BACKUP_DIR=${BACKUP_DIR:-$DEFAULT_BACKUP_DIR}
# Check if the directory to compress exists
if [ ! -d "$DIR_TO_COMPRESS" ]; then
echo "Error: The directory '$DIR_TO_COMPRESS' does not exist."
exit 1
fi
# Check if the backup directory exists or can be created
if [ ! -d "$BACKUP_DIR" ]; then
echo "The backup directory '$BACKUP_DIR' does not exist. Creating it now..."
mkdir -p "$BACKUP_DIR"
if [ $? -ne 0 ]; then
echo "Error: Could not create backup directory '$BACKUP_DIR'."
exit 1
fi
fi
# Get the base name of the directory to compress
BASE_NAME=$(basename "$DIR_TO_COMPRESS")
# Create the tar.gz file without including the directory structure
tar -czvf "${BACKUP_DIR}/${BASE_NAME}.tar.gz" -C "$DIR_TO_COMPRESS" .
# Check if the tar command was successful
if [ $? -eq 0 ]; then
echo "Backup created successfully at ${BACKUP_DIR}/${BASE_NAME}.tar.gz"
else
echo "Error: Failed to create the backup."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment