~/error.txt...">

Why does "java -version" output its output to the error stream?

Let's try redirecting the standard error for java :

 java -version 2> ~/error.txt 

error.txt populated with the version.

Let's try redirecting standard output:

 java -version > ~/output.txt 

output.txt empty.

Why is java binary output of normal output to the error stream?

+6
source share
2 answers

According to the Java documentation :

-showversion

Displays version information and continues to run the application. This option is equivalent to the -version option, except that the latter tells the JVM to exit after version information is displayed.

-version

Displays version information and then exits. This option is equivalent to the -showversion option, except that the latter does not tell the JVM to exit after version information is displayed.

Now consider the Wikipedia definition for stderr :

A standard error is another output stream that is commonly used by programs to display error messages or diagnose.

Most POSIX-oriented tools require a very careful specification for the stdout stream, so the output of the tool can be transferred elsewhere. Stderr is much less prescribed and used for logging and errors.

With -showversion Java allows you to print version information next to a running application. However, if the version information was printed on stdout , it would be indistinguishable from the usual application output, which could accompany it, forcing you to scan and delete this line of output yourself. Of course, with -version instead of -showversion the version string is most likely the intended output, but maintaining consistency is a fitting end in itself.

For what it's worth, printing the requested metadata in stderr vs stdout is something open-ended , so little can be said about the โ€œstandard practiceโ€ for each application.

To get around this, simply redirect stderr to stdout:

 VERSION=$(java -version 2>&1) 
+6
source

This seems to be a bug, or simply inconsistency, that the java command compared to many other commands in releasing UNIX version output for stdout:

mvn -v > ~/output.txt # works as expected

There is a mistake for him, but it was closed. Oracle probably cannot solve the problem, as it can cause problems for systems that expect them to behave this way.

+1
source

All Articles