How to access Java property in terminal - java

I know I can get all the Java System properties from the terminal using
java -XshowSettings:properties -version
How do I access just one specific java system property?
For example, like "user.name"?
I want to do this in the terminal, not with Java.

Solution as a one liner script. Just change the val variable to the key you want to print:
val='java.library.path'; java -XshowSettings:properties -version 2>&1 | sed -re 's/^ +[^=]+ =/_&/' | gawk -v key=$val 'BEGIN{ RS="_"; IFS=" = "} { if($1 ~ key){ print $0 }}'
Details
Some property values like java.library.path contain new lines so we need to mark records before filtering and printing them.
sed allows us to do that, then awk can be used to filter and print.
java -XshowSettings:properties -version 2>&1 |\
sed -re 's/^ +[^=]+ =/_&/' |\
gawk -v key=java.library.path 'BEGIN{ RS="_"; IFS=" = "} { if($1 ~ key){ print $0 }}'
Result:
java.library.path = /usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
Pipeline parts explained:
2>&1: properties are printed to stderr so we need to redirect them to stdin.
sed -re 's/^ +[^=]+ =/_&/' : add an underscore in front of interesting lines, those starting with 4 spaces and containing =.
gawk -v key=java.library.path: set keyawk variable to the selected property key.
'BEGIN{ RS="_"; IFS=" = "}: set record separator to '_' and input field separator IFS to =.

If you need the current logged in user in bash just use whoami command. If you want to get the java property from terminal you can use the following command
java -XshowSettings:properties -version 2>&1 | grep user.name
which will print
$java -XshowSettings:properties -version 2>&1 | grep user.name
user.name = user
If you just need the user name only
java -XshowSettings:properties -version 2>&1 | grep user.name | cut -c 16-100
which will print
$java -XshowSettings:properties -version 2>&1 | grep user.name | cut -c 16-100
user

You can't.
What you can do is create a java file to get the information and run with java, here the documentation.
Since you already said that you don't want this, you can grep (filter) the output of
java -XshowSettings:properties -version 2>&1 | grep java.home
java.home = /usr/java/jdk1.8.0_112/jre
If you want to know the system properties of a running jvm, use the jcmd tool
jcmd PID VM.system_properties

Related

Get the Java version in specific format using bash

My Java version is:
openjdk version "1.8.0_312"
OpenJDK Runtime Environment (build 1.8.0_312-b07)
OpenJDK 64-Bit Server VM (build 25.312-b07, mixed mode)
How can I get the Java version in below format using bash script:
1.8.0
I tried multiple options like java -version 2>&1 | head -n 1 | cut -d'"' -f2, but I'm unable to get the desired output.
To check for a string (your expected version), you can use grep:
if java -version 2>&1 | head -n 1 | grep --fixed-strings '"1.8.0'
then echo expected version
else echo unexpected version
fi
Note the --fixed-strings (short -F), otherwise grep treats . as a RegEx and it will match any character. Thx Gorodon for pointing that out!
I also added the leading " quote so it will not match 11.8.0.
$ IFS='"_' read -r _ ver _ < <(java -version 2>&1)
$ echo "$ver"
1.8.0
You can try this one
java --version | head -n1 |cut -d " " -f1,2
output
openjdk 8.0
You can use grep (or egrep) to print matching patterns:
java --version | head -n 1 | grep -Po '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'
java --version | head -n 1 | egrep -o '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'

grep md5has from java command

I have tried many combinations, but I can't get a specific string from a Java command to generate an md5 hash:
java -cp /var/lib/rundeck/bootstrap/jetty-all-7.6.0.v20120127.jar org.eclipse.jetty.util.security.Password admin outsideit.net | grep -o "^MD5"
outsideit.net
OBF:1y0q1w9b1xtx1l1g155w1toa1t331tok1wui1kxm1xtl1w8f1y10
MD5:a7da14229ea147aaa364e503947cbe35
CRYPT:adiwf3pJ9m8Vw
Whichever grep statement I try it always outputs the above.
As the java command throws the output as stderr, the bash will not be able to grep it untill you specify "&> >(grep MD5)" instead of " | grep ". The below command show work for you.
java -cp /var/lib/rundeck/bootstrap/jetty-all-7.6.0.v20120127.jar org.eclipse.jetty.util.security.Password admin outsideit.net &> >(grep MD5)

Python - how can i read in and read out so that other readers can read it for further pursing?

I have to run the Java application and read the syslog to trigger some other Python based events.
At the same time i also need to dump and store it in /var/tmp/log.log of all java outputs, but because the new Python event controller is added that /var/tmp/log.log i was not able to create. Any idea how can i still make it? . For example: java | python >> java logs as >> log.log for tail -f
BEFORE: (worked)
$ java -cp /var/tmp/Audio.jar Main.Boot >> /var/tmp/log.log &
$ tail -f /var/tmp/log.log
AFTER: (not working)
$ java -cp /var/tmp/Audio.jar Main.Boot | python -u /var/tmp/consumer.py &
$ tail -f ????? how can i have the java syslog still dumped as like my BEFORE ????
/var/tmp/consumer.py
import sys, time, os
while True:
line = sys.stdin.readline()
if line:
sys.stdout.flush()
if "wall:on" in line:
os.system("/var/tmp/me.sh")
else:
time.sleep(1)
/var/tmp/me.sh
#!/bin/bash
export DISPLAY=:0.0
ps aux | grep "/var/tmp/pp.py" | awk '{print $2}' | xargs kill -9;
# System maintain..
python /var/tmp/pp.py &
sleep 3
ps aux | grep "/var/tmp/pp.py" | awk '{print $2}' | xargs kill -9;
Off the top of my head:
$ java -cp /var/tmp/Audio.jar Main.Boot | tee /var/tmp/log.log | python -u /var/tmp/consumer.py &
$ tail -f /var/tmp/log.log
I would also do the awk/grep stuff inside python instead of going through a subprocess.

How to get Java Version from batch script?

I am trying to get '6' out of the java version output given below
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
For the same I wrote this batch script
set VERSION6="1.6.0_21"
java -version 2>&1 | findstr "version" >ab.txt
for /f "tokens=3" %%g in (ab.txt) do (
if not %%g == %VERSION6% echo %%g
echo %%g
)
%%g displays "1.6.0_21"
May someone guide me to correct direction? I am not much familiar with for /f.
#echo off
setlocal
set VERSION6="1.6.0_21"
for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
#echo Output: %%g
set JAVAVER=%%g
)
set JAVAVER=%JAVAVER:"=%
#echo Output: %JAVAVER%
for /f "delims=. tokens=1-3" %%v in ("%JAVAVER%") do (
#echo Major: %%v
#echo Minor: %%w
#echo Build: %%x
)
endlocal
In the first for loop, "tokens=3" says that we're going to just use the third token from the command output. Rather than redirect the output of the java -version command to a file, we can run this command within the for loop itself. The carets (^) are escape characters, and are needed so we can embed the >, & and | symbols in the command string.
Within the body of the for loop, we set a new var, JAVAVER, so that we can do some manipulation of the version string later.
The set JAVAVER=%JAVAVER:"=% command removes the double quotes from around the version string.
The last for loop parses the java version string. delims=. says we're going to delimit tokens using periods. tokens=1-3 says we're going to pass the first three tokens from the string to the body of the loop. We can now get the components of the java version string using the explicit variable, %%v and the implied variables (next letters in the alphabet) %%w and %%x.
When I run this on my system I get:
Output: "1.6.0_24"
Output: 1.6.0_24
Major: 1
Minor: 6
Build: 0_24
I've made some modification to Patrick's answer so it works with Java 9, 10, etc.
This returns minor version for 1.x, and major version for Java 9, 10, etc.
#echo off
setlocal
rem We use the value the JAVACMD environment variable, if defined
rem and then try JAVA_HOME
set "_JAVACMD=%JAVACMD%"
if "%_JAVACMD"=="" (
if not "%JAVA_HOME%"=="" (
if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"
)
)
if "%_JAVACMD%"=="" set _JAVACMD=java
rem Parses x out of 1.x; for example 8 out of java version 1.8.0_xx
rem Otherwise, parses the major version; 9 out of java version 9-ea
set JAVA_VERSION=0
for /f "tokens=3" %%g in ('%_JAVACMD% -Xms32M -Xmx32M -version 2^>^&1 ^| findstr /i "version"') do (
set JAVA_VERSION=%%g
)
set JAVA_VERSION=%JAVA_VERSION:"=%
for /f "delims=.-_ tokens=1-2" %%v in ("%JAVA_VERSION%") do (
if /I "%%v" EQU "1" (
set JAVA_VERSION=%%w
) else (
set JAVA_VERSION=%%v
)
)
#echo %JAVA_VERSION%
endlocal
echoes 8 or 17 etc.
This will extract the minor part of the version number:
java -version 2>&1 | awk '/version/ {print $3}' | awk -F . '{print $2}'
However, it may be better to extract the major.minor and match on that in case Oracle ever change the version number scheme again e.g.:
java -version 2>&1 | awk '/version/ {print $3}' | egrep -o '[0-9]+\.[0-9]+'
for /f tokens^=2-5^ delims^=.-_+^" %j in ('java -fullversion 2^>^&1') do #set "jver=%j%k%l%m"
This will store the java version into jver variable and as integer
And you can use it for comparisons .E.G
if %jver% LSS 16000 echo not supported version
.You can use more major version by removing %k and %l and %m.This command prompt version.
For .bat use this:
#echo off
PATH %PATH%;%JAVA_HOME%\bin\
for /f tokens^=2-5^ delims^=.-_+^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j%%k%%l%%m"
According to my tests this is the fastest way to get the java version from bat (as it uses only internal commands and not external ones as FIND,FINDSTR and does not use GOTO which also can slow the script). Some JDK vendors does not support -fullversion switch or their implementation is not the same as this one provided by Oracle (better avoid them).

Running Different Bash Commands Based on Java Version

I'm trying to develop a bash build script for a Java project that will be run on Ubuntu and Fedora. Ubuntu uses the gcj compiler while Fedora uses IcedTea.
Both report their errors and warning in slightly different ways, and I want to ignore the warnings (I know, not generally a good idea, but some of the warnings are simply idiotic).
For gcj, I want to run:
javac *.java 2>&1 | grep -A 4 "error:"
but for IcedTea, I want to run:
javac *.java 2>&1 | grep -A 4 "error:\|errors\|.java:"
I'm still new to bash, so how would I write an if statement that would run one versus the other based upon the javac version?
Assuming your java and javac binaries match, and that icedtea is the special case.
#!/bin/bash
ERROR="error:"
java -version 2>&1 | grep -i icedtea > /dev/null
if [ $? -eq 0 ]; then
ERROR="error:\|errors\|.java:"
fi
javac *.java 2>&1 | grep -A 4 $ERROR
On my system, icedtea and sun have the same output for "javac -version", but not for "java -version".
Writing Java build scripts in bash (or any other shell language) has a number of problems:
scripts tend to be non-portable due to shell differences, different command locations, incompatible command options and so on ... even if you try to make the portable.
scripts cannot cope with dependencies (or at least not easily)
scripts cannot cope with recompiling only stuff that has changed
Instead, I suggest that you write a "build.xml" file and use the Ant build tool. Ant has the advantage of running on any build platform that runs Java, and of taking care of the vast majority of platform differences. It is sort of like a better "Make" designed specifically for building Java.
#!/bin/sh
JAVAC_VERSION="`java -version 2>&1 /dev/null | awk '/IcedTea/ {print $4}' | sed -e 's/[\(0-9]//g'`"
ICEDTEA="IcedTea"
if [ ${JAVAC_VERSION} = ${ICEDTEA} ]; then
javac *.java 2>&1 | grep -A 4 "error:\|errors\|.java:"
else
javac *.java 2>&1 | grep -A 4 "error:"
fi
exit 0
That should do it - if i understood your question correctly. How you get the version - im not quite sure of, but if my javac -version is incorrect just change it accordingly to your needs.

Categories