I want to create a bash script to backup and restore the project (apache, mariadb and php) easily. I need to work at 2 debian machine with the same configuration in 2 different location. I ask to duck.ai to solve the problem. Here is the result.
Create a file myconfig.conf
# myconfig.confDB_NAME="your_database_name"DB_USER="your_username"DB_PASS="your_password"PROJECT_ROOT="/path/to/your/php/project" # Add this line
Create bash script mybackup.sh
#!/bin/bash# Load database configuration from myconfig.confsource myconfig.conf# Create a backup file name for the databaseDB_BACKUP_FILE="${DB_NAME}_$(date +%Y-%m-%d).sql"# Create a zip file name for the projectPROJECT_BACKUP_FILE="$(basename "$PROJECT_ROOT")_backup_$(date +%Y-%m-%d).zip"# Function to backup the databasebackup_database() { echo "Backing up database: $DB_NAME" mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" > "$DB_BACKUP_FILE" if [ $? -eq 0 ]; then echo "Database backup successful: $DB_BACKUP_FILE" else echo "Database backup failed!" return 1 fi}# Function to zip the project fileszip_project() { echo "Zipping project files from: $PROJECT_ROOT" zip -r "$PROJECT_BACKUP_FILE" "$PROJECT_ROOT" if [ $? -eq 0 ]; then echo "Project backup successful: $PROJECT_BACKUP_FILE" else echo "Project backup failed!" return 1 fi}# Function to restore the databaserestore_database() { echo "Restoring database: $DB_NAME from $1" mysql -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" < "$1" if [ $? -eq 0 ]; then echo "Database restore successful!" else echo "Database restore failed!" fi}# Function to unzip the project filesunzip_project() { echo "Unzipping project files to: $PROJECT_ROOT" unzip -o "$1" -d "$PROJECT_ROOT" if [ $? -eq 0 ]; then echo "Project restore successful!" else echo "Project restore failed!" fi}# Check command line argumentsif [ "$1" == "backup" ]; then backup_database zip_projectelif [ "$1" == "restore" ]; then if [ -z "$2" ] || [ -z "$3" ]; then echo "Please provide the SQL backup file and the project zip file to restore from." exit 1 fi SQL_BACKUP_FILE="$2" PROJECT_BACKUP_FILE="$3" restore_database "$SQL_BACKUP_FILE" unzip_project "$PROJECT_BACKUP_FILE"else echo "Usage: $0 {backup|restore [sql_backup_file] [project_backup_file]}" exit 1fi
To backup
./mybackup.sh backup
It will create 2 files
- zip for backup and restore web root project
- sql for backup and restore mariadb database
To restore
./mybackup.sh restore your_database_backup.sql your_project_backup_file.zip