Introduction
Installing Magento 2.4.7 on macOS can be a daunting task, especially if you’re manually handling each step. Automation not only saves time but also minimizes errors, ensuring a smooth setup process. In this guide, we’ll walk you through a Bash script that automates the installation of Magento 2.4.7 on a Mac. We’ll break down the script into sections, explaining each part in detail—perfect for junior developers looking to understand the process.
Keywords: Magento 2.4.7 installation, macOS, Bash script, automation, e-commerce development
Prerequisites
Before you begin, make sure you have:
- A Mac running the latest version of macOS
- Administrative privileges
- Homebrew installed
- Basic knowledge of Terminal commands
Step-by-Step Breakdown of the Bash Script
1. Script Initialization and Settings
First, we start the script and set options to ensure it runs correctly.
bashCopy code#!/bin/bash
# Start time to benchmark script duration
start=$(date +%s)
# Exit immediately if a command exits with a non-zero status,
# Treat unset variables as an error, and prevent errors in a pipeline from being masked
set -euo pipefail
Explanation:
#!/bin/bash
: Shebang line specifying the script should be run in Bash.start=$(date +%s)
: Captures the start time to calculate how long the script takes to run.set -euo pipefail
: Sets strict error handling to prevent the script from continuing if an error occurs.
2. Defining Color Codes for Output
To make the script output more readable, we define color codes for different log levels.
bashCopy code# Color codes for output
BOLD_RED='\033[1;31m'
BOLD_GREEN='\033[1;32m'
BOLD_YELLOW='\033[1;33m'
BOLD_CYAN='\033[1;36m'
RESET='\033[0m'
Explanation:
- These variables store ANSI color codes to style the output text in the terminal.
3. Creating Log Functions
We define functions to standardize how messages are logged.
bashCopy code# Log function with color-coded messages
log() {
local level=$1
shift
echo -e "[$(date +'%Y-%m-%d %H:%M:%S')] [${level}] $*" >&2
}
error() { log "${BOLD_RED}ERROR${RESET}" "$@"; }
success() { log "${BOLD_GREEN}SUCCESS${RESET}" "$@"; }
info() { log "${BOLD_CYAN}INFO${RESET}" "$@"; }
warning() { log "${BOLD_YELLOW}WARNING${RESET}" "$@"; }
Explanation:
log()
: General logging function that includes a timestamp and log level.error()
,success()
,info()
,warning()
: Helper functions that calllog()
with appropriate styles.
4. Defining Dependencies
We specify the dependencies required for Magento and how to check for them.
bashCopy code# macOS specific variables
PACKAGE_INSTALL_CMD="brew install"
# Dependencies list (with corresponding check commands)
DEPENDENCIES=("php@8.2" "composer" "mysql" "nginx" "node" "npm" "opensearch" "imagemagick" "redis")
DEPENDENCY_COMMANDS=("php" "composer" "mysql" "nginx" "node" "npm" "opensearch" "magick" "redis-server")
Explanation:
PACKAGE_INSTALL_CMD
: Command to install packages using Homebrew.DEPENDENCIES
: Array of packages to install.DEPENDENCY_COMMANDS
: Corresponding commands to verify if each dependency is installed.
5. Checking and Installing Dependencies
This function ensures all necessary software is installed.
bashCopy code# Function to check and install dependencies using Homebrew
check_dependencies() {
info "Checking and installing dependencies for macOS..."
for ((i=0; i<${#DEPENDENCIES[@]}; i++)); do
dep_name="${DEPENDENCIES[$i]}"
dep_command="${DEPENDENCY_COMMANDS[$i]}"
if ! command -v "$dep_command" &> /dev/null; then
info "$dep_name is required but not installed. Installing..."
$PACKAGE_INSTALL_CMD "$dep_name" || error "Failed to install $dep_name. Please install it manually."
else
success "$dep_name is already installed."
fi
done
}
Explanation:
- Loops through each dependency, checks if it’s installed, and installs it if not.
- Uses
command -v
to check for the presence of each command.
6. Starting Essential Services
We ensure that necessary services are running before proceeding.
bashCopy code# Function to check and start services
check_and_start_services() {
local services=("mysql" "redis" "opensearch")
for service in "${services[@]}"; do
if ! brew services list | grep -q "^$service.*started"; then
warning "$service is not running. Attempting to start..."
brew services start "$service" || error "Failed to start $service. Please check manually."
success "$service started successfully."
else
success "$service is already running."
fi
done
}
Explanation:
- Checks if each service is running using
brew services list
. - Starts the service if it’s not already running.
7. Managing Nginx Service
We handle Nginx separately to avoid configuration conflicts during installation.
bashCopy code# Function to check and manage Nginx service
stop_nginx() {
if brew services list | grep -q "^nginx.*started"; then
info "Stopping Nginx to prevent configuration conflicts..."
brew services stop nginx || warning "Failed to stop Nginx. Proceeding..."
fi
}
reload_or_restart_nginx() {
if brew services list | grep -q "^nginx.*started"; then
info "Reloading Nginx configuration..."
nginx -s reload || { warning "Reload failed. Restarting Nginx..."; brew services restart nginx; }
else
info "Starting Nginx..."
brew services start nginx || error "Failed to start Nginx. Please check configuration manually."
fi
}
Explanation:
stop_nginx()
: Stops Nginx if it’s running.reload_or_restart_nginx()
: Reloads or restarts Nginx after installation.
8. Loading Configuration from YAML File
We use a YAML file to store site-specific configurations.
bashCopy code# Path to configuration file with site settings
CONFIG_FILE="./config/magento_sites_config.yaml"
# Function to load configuration for a specific site
load_config() {
local site_name=$1
INSTALL_PATH=$(yq e ".sites.${site_name}.install_path" "$CONFIG_FILE")
BASE_URL=$(yq e ".sites.${site_name}.base_url" "$CONFIG_FILE")
DB_HOST=$(yq e ".sites.${site_name}.db_host" "$CONFIG_FILE")
DB_NAME=$(yq e ".sites.${site_name}.db_name" "$CONFIG_FILE")
DB_USER=$(yq e ".sites.${site_name}.db_user" "$CONFIG_FILE")
DB_PASSWORD=$(yq e ".sites.${site_name}.db_password" "$CONFIG_FILE")
ADMIN_FIRSTNAME=$(yq e ".sites.${site_name}.admin_firstname" "$CONFIG_FILE")
ADMIN_LASTNAME=$(yq e ".sites.${site_name}.admin_lastname" "$CONFIG_FILE")
ADMIN_EMAIL=$(yq e ".sites.${site_name}.admin_email" "$CONFIG_FILE")
ADMIN_USER=$(yq e ".sites.${site_name}.admin_user" "$CONFIG_FILE")
ADMIN_PASSWORD=$(yq e ".sites.${site_name}.admin_password" "$CONFIG_FILE")
BACKEND_FRONTNAME=$(yq e ".sites.${site_name}.backend_frontname" "$CONFIG_FILE")
}
Explanation:
- Uses the
yq
command to parse the YAML file and load configurations. - Ensure you have
yq
installed:
bashCopy codebrew install yq
9. Setting Up the Database
We create the database and user for Magento.
bashCopy code# Set up the database
setup_database() {
info "Setting up database: $DB_NAME..."
mysql -u root -e "CREATE DATABASE IF NOT EXISTS $DB_NAME;"
mysql -u root -e "CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASSWORD';"
mysql -u root -e "GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost';"
}
Explanation:
- Executes MySQL commands to set up the database and user.
- Grants necessary privileges to the Magento database user.
10. Installing Magento
We download and install Magento using Composer.
bashCopy code# Install Magento
install_magento() {
info "Installing Magento in $INSTALL_PATH..."
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition=2.4.7 "$INSTALL_PATH" --prefer-dist --no-interaction
cd "$INSTALL_PATH"
cp nginx.conf.sample nginx.conf
# Set file permissions
find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
chmod u+x bin/magento
chown -R "$USER":"$(id -g -n "$USER")" "$INSTALL_PATH"
}
Explanation:
- Uses Composer to create a new Magento project.
- Copies the sample Nginx configuration file.
- Sets appropriate permissions to prevent file access issues.
11. Configuring Magento
We run Magento’s setup script with the loaded configurations.
bashCopy code# Configure Magento
configure_magento() {
info "Configuring Magento..."
php bin/magento setup:install \
--base-url="$BASE_URL" \
--db-host="$DB_HOST" \
--db-name="$DB_NAME" \
--db-user="$DB_USER" \
--db-password="$DB_PASSWORD" \
--admin-firstname="$ADMIN_FIRSTNAME" \
--admin-lastname="$ADMIN_LASTNAME" \
--admin-email="$ADMIN_EMAIL" \
--admin-user="$ADMIN_USER" \
--admin-password="$ADMIN_PASSWORD" \
--language="en_US" \
--currency="USD" \
--timezone="America/New_York" \
--use-rewrites="1" \
--backend-frontname="$BACKEND_FRONTNAME"
}
Explanation:
- Runs the Magento installation command with all necessary options.
- Configures the admin user and store settings.
12. Running the Main Function
We compile all the functions into the main execution flow.
bashCopy code# Main function to run the deployment
main() {
check_dependencies
check_and_start_services
# Load config
load_config "site1"
# Stop Nginx if needed
stop_nginx
# Set up directory and database
rm -rf "$INSTALL_PATH" && mkdir -p "$INSTALL_PATH"
setup_database
install_magento
configure_magento
# Reload or restart Nginx
reload_or_restart_nginx
success "Magento installation completed."
}
main
Explanation:
- Calls each function in the correct order.
- Removes any existing installation in the
INSTALL_PATH
to start fresh.
13. Calculating Script Duration
At the end, we calculate how long the script took to run.
bashCopy code# Calculate script duration
end=$(date +%s)
echo "Script run in: $((end-start)) seconds"
Explanation:
- Captures the end time and calculates the total duration.
Conclusion
By automating the Magento installation process with this Bash script, you can set up a Magento 2.4.7 environment on macOS efficiently and consistently. This guide breaks down each part of the script, making it accessible even for those new to Bash scripting or Magento development.
Best Practices and Potential Pitfalls
- Keep Dependencies Updated: Regularly update your dependencies to the latest versions.
- Secure Credentials: Use strong, unique passwords for your database and admin accounts.
- Backup Configurations: Always backup your configuration files before making changes.
- Test the Script: Run the script in a test environment before deploying to production.
SEO Meta Description
Automate Magento 2.4.7 installation on macOS using a Bash script. Step-by-step guide breaking down the script for easy understanding and implementation.
Call-to-Action
Need expert assistance with your e-commerce platform? At Adepapa, we specialize in optimizing Magento installations for performance and scalability. Contact us today to elevate your e-commerce success.