Problem scenario
You want to install Maven with a script. You want the script to work regardless of what distribution of Linux you are using (e.g., Ubuntu/Debian, RedHat (including CentOS/Fedora), or SUSE). How do you write a script to install the latest version of Maven?
Solution
Update: This script was updated on 9/23/19.
1. Create this file in /tmp/ and call it maven.sh. Below is the content:
#!/bin/bash
# Written by www.continualintegration.com
mvnversion=3.6.2 # Change this version as necessary
distro=$(cat /etc/*-release | grep NAME)
debflag=$(echo $distro | grep -i "ubuntu")
if [ -z "$debflag" ]
then # If it is not Ubuntu, test if it is Debian.
debflag=$(echo $distro | grep -i "debian")
echo "determining Linux distribution..."
else
echo "You have Ubuntu Linux!"
fi
rhflag=$(echo $distro | grep -i "red*hat")
if [ -z "$rhflag" ]
then #If it is not RedHat, see if it is CentOS or Fedora.
rhflag=$(echo $distro | grep -i "centos")
if [ -z "$rhflag" ]
then #If it is neither RedHat nor CentOS, see if it is Fedora.
echo "It does not appear to be CentOS or RHEL..."
rhflag=$(echo $distro | grep -i "fedora")
fi
fi
if [ -z "$rhflag" ]
then
echo "...still determining Linux distribution..."
else
echo "You have a RedHat distribution (e.g., CentOS, RHEL, or Fedora)"
yum -y install java-1.8.0-openjdk*
JAVA_HOME=/usr/lib/jvm/jre-1.8.0-openjdk
echo 'export JAVA_HOME=/usr/lib/jvm/jre-1.8.0-openjdk' >> ~/.bashrc
source ~/.bashrc
source /etc/environment
fi
if [ -z "$debflag" ]
then
echo "...still determining Linux distribution..."
else
echo "You are using either Ubuntu Linux or Debian Linux."
apt-get -y update # This is necessary on new AWS Ubuntu servers.
apt -y install openjdk-9-jre-headless default-jdk
apt -y install openjdk-11-jre-headless
echo "If you see an error about an installation candidate, do not be concerned"
sleep 2
fi
suseflag=$(echo $distro | grep -i "suse")
if [ -z "$suseflag" ]
then
if [ -z "$debflag" ]
then
if [ -z "$rhflag" ]
then
echo "*******************************************"
echo "Could not determine the Linux distribution!"
echo "Installation aborted. Nothing was done."
echo "******************************************"
exit
fi
fi
else
zypper -n install java-1_8_0-openjdk java-1_8_0-openjdk-devel
fi
curl http://ftp.wayne.edu/apache/maven/maven-3/$mvnversion/binaries/apache-maven-$mvnversion-bin.tar.gz > /bin/apache-maven-$mvnversion-bin.tar.gz
cd /bin
tar -xvf apache-maven-$mvnversion-bin.tar.gz
mkdir -p /usr/local/apache-maven
mv /bin/apache-maven-$mvnversion/* /usr/local/apache-maven
if [ -z "$debflag" ]
then
/usr/bin/ln -s /usr/local/apache-maven/bin/mvn /bin/mvn
else
/bin/ln -s /usr/local/apache-maven/bin/mvn /bin/mvn
fi
echo 'PATH="$PATH":/usr/local/apache-maven/bin/' > /etc/profile.d/maven.sh
echo 'To finish the process, run this command:'
echo 'export PATH="$PATH":/usr/local/apache-maven/bin/'
echo "Then run 'mvn -version' to see if Maven is installed."
2. Run it with this command: sudo -s source /tmp/maven.sh