0

I'm just learning batch script. I'm reviewing the getJavaVersion.bat script on GitHub. I understood what the 2^>^&1 expression in the following line of code is used for. But I couldn't understand how this syntax (2^>^&1) is used. Can you help me with this?

for /f tokens^=2-5^ delims^=.-_^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j%%k%%l%%m"

The commands below show the generated values:

for /f "delims=" %%i in ('java -fullversion') do set output=%%i
echo %output%
:: OUTPUT >> java full version "18.0.1.1+2-6"

for /f tokens^=2-5^ delims^=.-_^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j%%k%%l%%m"
echo %jver%
:: OUTPUT >> 18011+2
George Sun
  • 85
  • 6
  • 3
    Please read about [escape characters](https://ss64.com/nt/syntax-esc.html) and about [redirection](https://ss64.com/nt/syntax-redirection.htmlI). – Some programmer dude May 18 '22 at 10:52
  • 1
    `java -version` or `java -fullversion` returns the output in the _STDERR_ stream (handle `2`) rather than in the _STDOUT_ stream (handle `1`). `for /F`, together with a command behind the `in` keyword, captures and parses the command output at the _STDOUT_ stream. To capture the _STDERR_ stream you need to redirect it by `2>&1`, meaning that handle `2` (_STDERR_) is redirected where handle `1` points to (_STDOUT_). To ensure that the redirection is not applied to the `for /F` command itself, you need to properly escape it… – aschipfl May 18 '22 at 11:45

1 Answers1

1

The command java -version or java -fullversion returns the output at the STDERR stream (handle 2) rather than at the STDOUT stream (handle 1). for /F, together with a command behind the in keyword, captures and parses the command output at the STDOUT stream. To capture the STDERR stream you need to redirect it by 2>&1, meaning that handle 2 (STDERR) is redirected where handle 1 points to (STDOUT). To ensure that the redirection is not applied to the for /F command itself, you need to properly escape it (^) in order for the special characters > and & to lose their particular meaning until the whole for /F command line was processed. The command to be captured eventually contains the redirection expression in an unescaped manner.

aschipfl
  • 33,626
  • 12
  • 54
  • 99