Within the code block
from the (
of the original if
to the very closing )
,
- labels are essentially illegal.
%var%
means the value of var
at the time the block was encountered, not the value as changed within the block.
- You need to invoke
delayedexpansion
to access the value of a variable that has changed.
Beware of the delayed expansion trap
if not defined "%JAVA_HOME%" (
asks whether the variable "%JAVA_HOME%"
is defined, so if java_home
is set to c:\somewhere
then if not defined "%JAVA_HOME%" (
will be interpreted as if not defined "c:\somewhere" (
. It's highly unlikely that a variable named "c:\somewhere"
has been defined, and not what you probably want.
This is a revised version which circumvents the problems - I believe. Since you don't show us the string produced by java -version
, I don't know the detail of processing it.
setlocal enabledelayedexpansion
set EXPECTED_JAVA_VERSION=10
if not defined JAVA_HOME (
for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
set "JAVAVER=%%g"
)
set "JAVAVER=!JAVAVER:"=!"
echo JAVAEVER!JAVAVER!
set "JAVA="
for /f "delims=. tokens=2" %%v in ("!JAVAVER!") do (
set "JAVA=%%v"
)
echo "!JAVA!"
)
IF "%JAVA%" LSS "%EXPECTED_JAVA_VERSION%" (echo JAVA VERSION is %JAVA% - need %expected_java_version%) ELSE (echo CORRECT JAVA VERSION)
If java_home
is not defined, then do the following:
- find the version of java from the third token of the string passed by
findstr
and assign to javaver
.
- using
delayed expansion
remove quotes from the now-changed value of javaver
. (Note that if %%g
is a string "enclosed in quotes" then %%~g
would have already removed those enclosing quotes.
- again
echo
the result.
- "set" the value of
java
to nothing, which undefines java
.
- set the value of
java
from the string in javaver
- display the result
Then it's a simple comparison - and please take the opportunity to produce an explanatory message.
BUT having done all this, I'd suggest that if java_home
is not defined, then java
is not installed at all, and you actually need to run your test if java IS installed, which implies java_home
would be set.