Skip to content

Instantly share code, notes, and snippets.

@gabrielbauman
Forked from seanorama/install-maven.sh
Last active April 27, 2023 17:04
Show Gist options
  • Save gabrielbauman/26a39fe3baaab79aaecb7c28bb616fab to your computer and use it in GitHub Desktop.
Save gabrielbauman/26a39fe3baaab79aaecb7c28bb616fab to your computer and use it in GitHub Desktop.
#!/bin/bash
# Drop this script in /usr/local/bin and run it with sudo to install/update to the latest maven. Keeps older versions around just in case.
# Works for me on Ubuntu, YMMV.
set -e
# Make sure we can write to /opt
if [ ! -w "/opt" ]; then
echo "/opt is not writeable. Try using sudo!"
exit 1;
fi
# Determine Maven version
mvn_version=`curl https://maven.apache.org/download.cgi --silent | grep "Downloading Apache Maven " | grep -oP '[0-9]+.[0-9]+.[0-9]+'`
# Bail if we already have the latest version
if [ -d ${version_dir} ]; then
echo "Maven ${mvn_version} is already installed. Nothing to do!"
exit 0
fi
# Build some URLs and paths
url="http://www.mirrorservice.org/sites/ftp.apache.org/maven/maven-3/${mvn_version}/binaries/apache-maven-${mvn_version}-bin.tar.gz"
install_dir="/opt/maven"
version_dir="${install_dir}/${mvn_version}"
# Make the target directory
mkdir -p "${version_dir}"
# Download and unpack the latest version
echo "Downloading Maven ${mvn_version}..."
curl -fsSL ${url} | tar zx --strip-components=1 -C ${version_dir}
# Update the symlink to point to the newly unpacked Maven
ln -sf ${version_dir} ${install_dir}/current
# Set up the environment
echo "Setting up environment..."
if [ -f /etc/profile.d/maven.sh ]; then
rm /etc/profile.d/maven.sh
fi
cat << EOF > /etc/profile.d/maven.sh
#!/bin/sh
export MAVEN_HOME=${install_dir}/current
export M2_HOME=${install_dir}/current
export M2=${install_dir}/current/bin
export PATH=${install_dir}/current/bin:\$PATH
EOF
echo "maven ${mvn_version} installed to ${version_dir} and set to current!"
echo
echo "To get mvn in your path, open a new shell or execute: source /etc/profile.d/maven.sh"
@gabrielbauman
Copy link
Author

This downloads to /opt/maven/x.x.x and sets /opt/maven/current symlink to point to the latest version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment