#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

# Check which CentOS version is installed
if [[ $(rpm -q --queryformat '%{VERSION}' centos-release) -eq 7 ]]; then
  # Install Apache on CentOS 7
  yum install -y httpd
  systemctl start httpd
  systemctl enable httpd
elif [[ $(rpm -q --queryformat '%{VERSION}' centos-release) -eq 8 ]]; then
  # Install Apache on CentOS 8
  dnf install -y httpd
  systemctl start httpd
  systemctl enable httpd
elif [[ $(rpm -q --queryformat '%{VERSION}' centos-release) -eq 9 ]]; then
  # Install Apache on CentOS 9
  dnf install -y httpd
  systemctl start httpd
  systemctl enable httpd
else
  echo "Unsupported CentOS version"
  exit
fi

# Add firewall rule to allow HTTP traffic
firewall-cmd --add-service=http --permanent
firewall-cmd --reload

echo "Apache web server installed and started successfully"

The script first checks if it is run as root, and exits if not.

It then checks which version of CentOS is installed using the rpm -q command.

Depending on the CentOS version, the script installs Apache web server using yum or dnf package manager, starts the service and enables it to start automatically on boot.

Finally, the script adds a firewall rule to allow HTTP traffic and reloads the firewall.

The script prints a message indicating that Apache web server has been installed and started successfully.

Note: This script assumes that you have a firewall enabled on your system. If you are using a cloud provider like AWS, make sure to add a rule to your security group to allow incoming HTTP traffic as well.

To run this bash script, follow these steps:

*Open a terminal on your CentOS machine.

*Create a new file using a text editor such as nano or vim.

*Copy and paste the entire script into the file.

*Save the file with a .sh extension, for example, “install_apache.sh”.

*Navigate to the directory where you saved the script file.

*Make the script executable by running the following command: chmod +x install_apache.sh

*Finally, run the script with root privileges by executing the following command: sudo ./install_apache.sh