I'm trying simple bash script:
/usr/libexec/java_home -V
output is:
Matching Java Virtual Machines (3):
11.0.1, x86_64: "Java SE 11.0.1" /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
10.0.1, x86_64: "Java SE 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
1.8.0_192, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home
Seems to be 4 lines, but if I try to get second line:
/usr/libexec/java_home -V | sed -n 2p
The output is the same. No additional line. If I try the first one - I got the second:
/usr/libexec/java_home -V | sed -n 1p
Output:
Matching Java Virtual Machines (3):
11.0.1, x86_64: "Java SE 11.0.1" /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
10.0.1, x86_64: "Java SE 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
1.8.0_192, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
If I assign output to array and count it's size:
array=( $(/usr/libexec/java_home -V) )
array_size=${#array[@]}
echo $array_size
it shows size = 1:
Matching Java Virtual Machines (3):
11.0.1, x86_64: "Java SE 11.0.1" /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
10.0.1, x86_64: "Java SE 10.0.1" /Library/Java/JavaVirtualMachines/jdk-10.0.1.jdk/Contents/Home
1.8.0_192, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home
1
What am I doing wrong?
What appears to be happening is that your script, /usr/libexec/java_home -V
is outputting some, or all, of its output to stderr
instead of writing to stdout
. Since the shell pipe ('|'
) connects the stdout
of the previous command to stdin
of the command that follows, any output to stderr
by /usr/libexec/java_home -V
just gets written to your screen and is never processed by sed
making it look like sed
wasn't working.
To test and correct the problem is that is the case, just redirect stderr
from your script to stdout
and then pipe the result to sed
, making sure sed
receives all of the output from your script, e.g.
$ /usr/libexec/java_home -V 2>&1 | sed -n 1p
Glad it helped.