2

Either I'm doing something silly or Sun is. How come something like:

java -version > version.txt

Still prints out to stdout and leaves version.txt empty? I'm checking out the exit code, and it's still 0, so is not that's writing to stderr.

I need this because I'm building a test-environment tool and want to check if the version of Java is adequate, I was planning to catch that version output, but now I'm stuck.

I'm on OS X Leopard, Java version 1.6.0_20.

Any ideas?

3 Answers 3

9
java -version &> version.txt

The exit code has nothing to do with where it outputs.

9
  • Could you please explain the & or at least say what it's called? It's really hard to search for in Google. May 20, 2010 at 9:41
  • Nice one, it works. Care to explain the difference between what I was doing and adding &? Thanks : ) May 20, 2010 at 9:42
  • > on its own only redirects stdout. &> redirects both stdout and stderr in most shells. May 20, 2010 at 10:06
  • 2
    @Ash: 2>&1 is the same in POSIX-compatible shells (bash, zsh, ash). The syntax is x>&y where x and y are file descriptors (1 for stdout, 2 for stderr). Only >& and &> are bash-specific extensions (which both mean 1>somefile 2>&1) May 20, 2010 at 12:32
  • 1
    @Yar, &> is a non-standard extension. Both bash and zsh know it though. Bare >& (no numbers) is also non-standard, but also both bash and zsh know it. All Bourne-like shells (including POSIX conforming shells) know x>&y. May 20, 2010 at 13:14
9

It's kind of a feature nowadays. ;-)

From an ancient bug report:

We should think very, very carefully before ever fixing this bug. It's obviously the wrong thing to print version information to stderr, but since we've been doing that since the beginning of time it seems likely that we'll break existing systems built on top of Java if we change it now. If we do decide to change this then it must wait until the Tiger release so that adequate testing can be done.

1
  • HA! What about that : ) Thank for the link to the bug, kind of makes me feel better. May 20, 2010 at 10:17
1

Just as an addition to Ignacio's answer:

Parsing the output of java -version is rather complex and error-prone (and the output is not guaranteed to always have the same format, especially with non-Sun JVMs).

To check the java version, you could run a small java program that checks the appropriate system properties: see Javadocs for getProperties(). This is the official, documented way to get information about the Java environment. You probably want to check:

  • java.version (exact version number of Java installation, e.g. 1.6.0_15 )
  • java.specification.version (the Java platform version, e.g. 1.5 or 1.6)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .