Search code examples
javabashcygwinjava-6

How can I quickly switch between JDKs in cygwin?


When working on the command line (using CYGWIN), I frequently need to switch between different versions of java. Are there any utilities that can take care of setting up JAVA_HOME, PATH etc. for me each time I need to switch?


Solution

  • I use a shell (bash, ksh, ...) function for this; Functions execute in the context of the current shell process and therefore can affect its environment:

    # Switch current JDK (JAVA_HOME) on Cygwin
    function jdkswitch {
        local version=$1
        local -a JDKS
        JDKS[8]='/cygdrive/c/apps/JDK/x64/jdk1.8.0_231'
        JDKS[11]='/cygdrive/c/apps/JDK/x64/jdk-11.0.5'
    
        if [[ -z ${version} ]] ; then
            echo "Current JDK: ${JAVA_HOME}"
            echo "Available JDKs: ${JDKS[*]}"
        else
            local jdkhome=${JDKS[${version}]}
            if [[ -d ${jdkhome} ]] ; then
                # Cygwin paths do not work for JAVA_HOME, must use Windows-style
                export JAVA_HOME=$(cygpath -w ${jdkhome})
                PATH=${jdkhome}/bin:${PATH}
                echo "Switched JDK to:"
                java -version
            else
                echo "Usage: jdkswitch version"
                echo "Available versions: ${!JDKS[*]}"
            fi
        fi
    }
    

    I typically save my functions one-per-file in ~/bin/functions and load them in my .profile (bash lacks the ksh "autoload" feature):

    FPATH=~/bin/functions
    for FUNC in ${FPATH}/* ; do
        . ${FUNC}
    done
    

    Then to switch JDK it's simply:

    $ jdkswitch 11
    

    There's a minor bug there where successive switches will prepend to the PATH each time, it might be fixable with some trickery but I've not experienced a problem to-date.

    As an aside (since the question specifies Cygwin), here is a MacOS version:

    # Switch current JDK (JAVA_HOME) based on available Mac installs
    function jdkswitch {
        local version=$1
        local jdkhome
        if [[ -z ${version} ]] ; then
            /usr/libexec/java_home --verbose
        else
            jdkhome=$(/usr/libexec/java_home -v${version})
            if [[ -d ${jdkhome} ]] ; then
                export JAVA_HOME=${jdkhome}
                echo "Switched to ${JAVA_HOME}"
                java -version
            fi
        fi
    }