Find out how three simple bash scripts can significantly simplify your work with the LAMP stack on Ubuntu. Creating and removing virtual hosts, setting up MySQL databases—everything becomes accessible even for beginner developers!

If you’ve ever felt like a cat that accidentally walked into a room with a running washing machine (everything is humming, and you’re just standing there wondering what’s happening), then you probably understand what I’m talking about. Working with the command line in Linux can be intimidating, especially if it’s only your second time encountering it (your first experience was likely during the setup and configuration of the LAMP stack).

But I’d like to ask you not to treat the command line as a monster living under your bed. The console simply wants you to learn how to use it properly. Meanwhile, I want to share with you three bash scripts that will help you automate repetitive tasks and make your first steps in web development easier.

Script 1: Creating a Virtual Host

When I first started working on web development under Linux and launched my first web server on Ubuntu 18.04, I was frustrated that every new project required me to perform the same actions over and over again: creating a directory, configuring Apache, editing /etc/hosts, and so on. It was like baking bread from scratch every time I wanted a sandwich—plowing the field, sowing rye, harvesting, and so forth.

So, drawing on my experience in automating technological processes and smart home systems, I decided to write a script that does all the dirty work for us.

Just run it, provide the name of your project and the domain name (e.g., mysite.local), and your site will be ready to go. All that’s left is to open the file in your editor, the site in your browser at the specified address, and let’s get rolling!

What Does Script 1 Do?

1 — Creates a directory for the site.
2 — Configures an Apache virtual host.
3 — Adds an entry to /etc/hosts.
4 — Creates a basic index.html file.

#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run this script with sudo."
  exit 1
fi

# Ask the user for the project name and domain
read -p "Enter the project name (e.g., mysite): " project_name
read -p "Enter the domain name (e.g., mysite.local): " domain_name

# Create the site directory inside /var/www
site_dir="/var/www/$project_name"
echo "Creating directory $site_dir..."
mkdir -p "$site_dir"

# Set ownership and permissions for the created directory
chown -R $USER:$USER "$site_dir"
chmod -R 755 "$site_dir"

# Create an index.html file with a welcome message
index_file="$site_dir/index.html"
echo "<html><body><h1>Welcome to $domain_name!</h1></body></html>" > "$index_file"

# Configure Apache virtual host
echo "Configuring virtual host for $domain_name..."
config_file="/etc/apache2/sites-available/$project_name.conf"
cat <<EOF > "$config_file"
<VirtualHost *:80>
    ServerAdmin webmaster@$domain_name
    ServerName $domain_name
    DocumentRoot $site_dir

    <Directory $site_dir>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/$project_name-error.log
    CustomLog \${APACHE_LOG_DIR}/$project_name-access.log combined
</VirtualHost>
EOF

# Enable the created virtual host
a2ensite "$project_name.conf"

# Reload Apache configuration
systemctl reload apache2

# Add an entry to /etc/hosts
echo "Adding an entry to /etc/hosts..."
echo "127.0.0.1 $domain_name" >> /etc/hosts

# Open the site in the browser
echo "Opening $domain_name in the browser..."
xdg-open "http://$domain_name" >/dev/null 2>&1

# Success message
echo "Site successfully created and available at http://$domain_name"

If you carefully examine this script, you can easily understand all its steps and, if necessary, adjust it to suit your needs. Each action is accompanied by detailed comments both in the script itself and during its execution.

Script 2: Removing a Virtual Host

Now imagine this scenario: you’ve created several test sites, but they’re no longer needed. What do you do? You could manually delete the Apache configuration files, clean up /etc/hosts, and remove directories. But why bother when you can use the second script to do it for you?

This script will display a list of all active virtual hosts, allow you to choose the one you want to remove, and perform all the necessary actions. Couldn’t be simpler!

What Does Script 2 Do?

1 — Displays a list of enabled virtual hosts.
2 — Removes the Apache configuration file.
3 — Deletes the entry from /etc/hosts.
4 — Deletes the site directory.

#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run this script with sudo."
  exit 1
fi

# Get the list of enabled virtual hosts
echo "Getting the list of enabled virtual hosts..."
enabled_sites=$(ls /etc/apache2/sites-enabled/ | sed 's/\.conf$//' | awk '{gsub(/^[0-9]*_/,""); print $0}')

# Exit if no sites are enabled
if [ -z "$enabled_sites" ]; then
  echo "No enabled virtual hosts found."
  exit 0
fi

# Display the list of virtual hosts
echo "List of enabled virtual hosts:"
select site in $enabled_sites; do
  if [ -n "$site" ]; then
    break
  else
    echo "Invalid choice. Please select a number from the list."
  fi
done

# Confirm deletion
read -p "Are you sure you want to delete the host '$site'? (y/n): " confirm
if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
  echo "Operation canceled."
  exit 0
fi

# Remove the Apache configuration file
config_file="/etc/apache2/sites-available/${site}.conf"
echo "Removing Apache configuration file: $config_file..."
rm -f "$config_file"

# Disable the virtual host
echo "Disabling virtual host $site..."
a2dissite "$site"

# Reload Apache configuration
systemctl reload apache2

# Remove the entry from /etc/hosts
echo "Removing entry from /etc/hosts..."
sed -i "/127.0.0.1\s\+$site/d" /etc/hosts

# Remove the site directory
site_dir="/var/www/$site"
echo "Removing site directory: $site_dir..."
rm -rf "$site_dir"

# Success message
echo "Host '$site' successfully deleted."

If you created hosts using the first script, the second script will work flawlessly without any adjustments. However, if you create hosts using a different method, you may need to make some changes. Again, the script is well-commented, which will help you understand its structure and sequence of actions.

Script 3: Creating a MySQL User and Database
The first time I installed a CMS on a local hosting environment, I felt lost when I had to manually create users and tables in MySQL. At that point, I had no experience working with databases, and the CMS manual didn’t clearly explain how to create databases, tables, users, and assign privileges. Therefore, this final—but equally important—script will help you create a new MySQL user and database. Forget about complicated commands and password requirements—this script will handle everything for you. It will even check whether your password meets modern security standards (at least 8 characters, including uppercase and lowercase letters, special characters).

Simply provide the username, password, and database name, and everything will be ready.

What Does Script 3 Do?

1 — Creates a new MySQL user.
2 — Verifies password strength.
3 — Creates a database.
4 — Grants the user full privileges to manage the created database.

#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run this script with sudo."
  exit 1
fi

# Check if MySQL is installed
if ! command -v mysql &> /dev/null; then
  echo "MySQL not found. Make sure MySQL is installed."
  exit 1
fi

# Function to check password strength
check_password_strength() {
  local password=$1
  if [[ ${#password} -lt 8 ]]; then
    echo "Error: Password must be at least 8 characters long."
    return 1
  fi
  if ! [[ "$password" =~ [A-Z] ]]; then
    echo "Error: Password must contain at least one uppercase letter."
    return 1
  fi
  if ! [[ "$password" =~ [a-z] ]]; then
    echo "Error: Password must contain at least one lowercase letter."
    return 1
  fi
  if ! [[ "$password" =~ [\!\@\#\$\%\^\&\*\(\)\,\.\?\"\'\:\{\}\|\<\>] ]]; then
    echo "Error: Password must contain at least one special character (!@#$%^&*(),.?\":{}|<>)."
    return 1
  fi
  return 0
}

# Ask the user for the MySQL username
read -p "Enter the new MySQL username: " mysql_user

# Ask for the password twice for confirmation
while true; do
  read -s -p "Enter the password for user $mysql_user: " mysql_password
  echo ""
  read -s -p "Confirm the password for user $mysql_user: " mysql_password_confirm
  echo ""

  # Check if passwords match
  if [ "$mysql_password" != "$mysql_password_confirm" ]; then
    echo "Passwords do not match. Try again."
    continue
  fi

  # Check password strength
  if ! check_password_strength "$mysql_password"; then
    continue
  fi

  break
done

# Ask for the database name
read -p "Enter the database name: " db_name

# Connect to MySQL using the root password
echo "Enter the MySQL root password:"
mysql_root_password=$(mysql -u root -p -e "SELECT 1" 2>&1 >/dev/null)

# Create the user and database
echo "Creating the user and database..."

# SQL commands to create the user, database, and assign privileges
mysql -u root -p <<EOF
  CREATE USER '$mysql_user'@'localhost' IDENTIFIED BY '$mysql_password';
  CREATE DATABASE IF NOT EXISTS $db_name;
  GRANT ALL PRIVILEGES ON $db_name.* TO '$mysql_user'@'localhost';
  FLUSH PRIVILEGES;
EOF

# Check the result of the commands
if [ $? -eq 0 ]; then
  echo "User '$mysql_user' and database '$db_name' successfully created."
else
  echo "An error occurred while creating the user or database."
  exit 1
fi

Now you can focus on coding instead of database setup.

All three scripts can be copied and pasted into your preferred text editor, or you can download them as an archive via the link. Extract it to a convenient location for future use.

How to Run the Scripts?

All scripts are designed to run from the terminal. Yes, I promised in the title that we’d bypass the command line, but sooner or later, you’ll have to dive into the world of the terminal, especially if you plan to work on serious projects, deploy them publicly, or develop general proficiency with the terminal—it’s useful not only for Linux users but sometimes even for Windows users.

So, let’s move on to running the scripts.

Open the terminal on your PC. If you’re using Ubuntu like me, you can quickly open the terminal using the shortcut Ctrl+Alt+T (this works in many Debian- or Ubuntu-based systems), or find the application called «Terminal» or «Console» in your app list.

Launched it? Great! Before you is your system’s command line. To run our automation scripts, you need to navigate to the directory where they are stored. Use the cd command, which stands for «change directory» (move to another directory).

For example, if your scripts are located in the folder ~/scripts (~ refers to the home directory of the user, so in this case, it would be /home/username/scripts), execute the following command:

cd ~/scripts

Using ~, you can quickly specify a path relative to your home directory. If you don’t know the exact filename of the script, you can use the ls command, which lists all files in the current directory:

:~/scripts$ ls
create_vhost.sh
remove_vhost.sh
create_mysql_db_user.sh

Now that we see the list of our scripts, to run a script, use the sudo bash command followed by the name of the desired script. For example, to run the script for creating a virtual host, type:

sudo bash create_vhost.sh

If you receive an error message saying the file is «not executable,» you may need to add execution permissions. Run the following command before launching the script:

chmod +x create_vhost.sh

Don’t be afraid to experiment! Every command is a tool that helps you control your system. These three scripts will become your first helpers on the path to automating routine tasks.

If something goes wrong, don’t despair—the terminal is always ready to retry the command until everything works perfectly. Or, it might lead to the «death» of your system.

Tip for Beginners
Before running any script from an untrusted source, study it carefully.

Think twice! Don’t Drink and Root!