Search code examples
bashpipepipingmacos-high-sierra

OSX bash piping in script not working as I expect


To get the java version I run this in bash (what I really want is 1.8 or 1.8.0_171)

$ java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)

In my test script just getting the first line would be OK so I execute this:

java -version | grep java 
echo return is $?

which returns this:

java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
return is 1

According to the man page grep's return indicates it had no errors but found no matches even so the results from "java -version" are printed.

I've tried grep with a few different search patterns and have tried sed and aux, using Google for help, as well with the same results.

What am I doing wrong?


Solution

  • java -version writes to standard error, not standard output, so grep isn't receiving any input.

    java -version 2>&1 | grep java
    

    should do what you expect.