Restoring your PATH on MacOS

The inevitable happened and while adding/removing some utils to my path, I messed up my .bash_profile and ended up with a PATH where I couldn’t run any commands.

To recover, the default PATH on MacOS should be:

export PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

From here.

Installing OpenJDK 11 on MacOS

If you download the .tar.gz for OpenJDK 11 direct from http://jdk.java.net/11/, there’s no obvious install instructions (at least that I can find) either on the OpenJDK website on in the .gz file. If you’ve done any fiddling with different JDK versions on MacOS before, you’ve probably come across the ‘/usr/libexec/java_home’ utility (see here for my previous article about this utility, and answers to this StackOverflow post which includes one of the most extensive and useful guides to running different JDK versions on MacOS that I’ve seen) which does a number of useful things relating to which JDK you’re currently using in your PATH:

/usr/libexec/java_home : shows you were the current JDK home is, eg:

/Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home

/usr/libexec/java_home -V : lists all installed JDKs, e.g.:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
10, x86_64: "Java SE 10" /Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home
1.8.0_151, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

To switch between JDKs, use /usr/libexec/java_home -v version (e.g. 10):

$ /usr/libexec/java_home -v 1.8.0_151
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

Knowing that your available JDKs are installed to /Library/Java/JavaVirtualMachines/ by default, moving the contents of the downloaded OpenJDK 11 dir from inside the .gz file to the same location would make sense.

Once you’ve moved it there, java_home -V now shows the new JDK in place:

$ /usr/libexec/java_home -V
Matching Java Virtual Machines (3):
11, x86_64: "OpenJDK 11" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10, x86_64: "Java SE 10" /Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home
1.8.0_151, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

Updating my aliases to quickly switch versions in my .bash_profile, I now have:

alias j11="export JAVA_HOME='/usr/libexec/java_home -v 11'; java -version"
alias j10="export JAVA_HOME=`/usr/libexec/java_home -v 10`; java -version"
alias j8="export JAVA_HOME=`/usr/libexec/java_home -v 1.8`; java -version"

Sourcing the .bash_profile (source .bash_profile) and then running each alias, now I’ve got OpenJDK 11 set up and ready to go!

$ j11
openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)