1

How can I find the java version and set that to a variable?

I've tried this:

for /f "tokens=*" %%a in ('java -version | find "version"') do (set var1=%%a)

but java isn't redirecting its output to find. Another post suggested this solution

java -version 2>&1 | findstr "version" >tmp.txt
for /f "tokens=*" %%x in (tmp.txt) do (set var1=%%x)
echo %var1%
del tmp.txt

but I would like to avoid using the temp file.

Gary
  • 13,303
  • 18
  • 49
  • 71
hexadecimal
  • 217
  • 1
  • 4
  • 12
  • 2
    If memory serves correctly, I think you have to escape the pipe like `^|` in the case of the first example What's wrong with the second? – Gary Jun 13 '15 at 19:17
  • In the first, the variable is not established, it does not show echo %var1% ¿? The second works but I have to use find. – hexadecimal Jun 13 '15 at 19:38
  • `for /f "tokens=*" %%a in ('java -version ^| find /I "version"') do (set var1=%%a)` gives the same result for `find` and `findstr` as well. @Gary make this an answer, man... – JosefZ Jun 13 '15 at 22:09
  • @JosefZ Thanks for the confirmation. It's been a minute since I've used Windows, so I wasn't sure. – Gary Jun 13 '15 at 22:22
  • I can be stubborn apologize but I can not see the output by echo var1: for / f "tokens = *" %% a in ('java -version ^ | find / I "version"') do (set var1 = %% a) echo first output echo %var1% echo second output – hexadecimal Jun 14 '15 at 05:29
  • possible duplicate of [How to get java version using single command in Windows command prompt?](http://stackoverflow.com/questions/7606607/how-to-get-java-version-using-single-command-in-windows-command-prompt) – Gary Jun 14 '15 at 19:39

1 Answers1

1

java.exe seems to output the version information at STDERR, so the correct code is:

for /f "tokens=*" %%a in ('java -version 2^>^&1 ^| find "version"') do (set var1=%%a)

As you can see, >, & and | are escaped with ^.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • Surprised to see why your answer wasn't upvoted and worse, not even marked as correct, works perfectly. Problem they must be facing is that your code needs to be saved in a file in batch format to work like a charm – ShayHaned Feb 13 '19 at 15:31
  • @ShayHaned, thanks! I didn't include the code for being executed directly in Command Prompt as the question is only tagged [tag:batch-file]; in Command Prompt you'd need to replace each `%%` by `%`... – aschipfl Feb 13 '19 at 16:24
  • Sure thing, and you really saved me hours of pain there :) But I just wanted to ask, if we were to directly execute the code in cmd, then apart of replacing each %% by % , would that also have an affect on *2^>^&1 ^|* part of the solution? Would greatly appreciate your response – ShayHaned Feb 13 '19 at 20:05