Home > Net >  What does "2^>^&1" mean in batch script?
What does "2^>^&1" mean in batch script?

Time:05-19

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

CodePudding user response:

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.

  • Related