Search code examples
bashjavac

Correct way to check Javac version in BASH script


I am trying to get the javac version in a bash script (intended for apks manipulation and builds).

I found a way to get the java version which may be similar but not the same (it does not work for javac).

P.S.: Currently working on OS X but should also work on Linux.

EDIT: PS: Some environments may not have javac in the PATH

Thanks!


Solution

  • Try this function that supports both cases, when javac is or is not in PATH variable

    showJavacVersion() 
    {
        x="h"
        {
            x=$(type -p javac)
        } >&-
        if [ -n "$x" ]; then
            _javac=javac
        elif [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/javac" ]];  then
            _javac="$JAVA_HOME/bin/javac"
        fi
        if [[ "$_javac" ]]; then
            version=$("$_javac" -version 2>&1 | awk -F ' ' '/javac/ {print $2}')
            echo $version
        else
            echo javac not found
        fi
    }
    

    Simply call it this way

    showJavacVersion
    

    Hope it helps!