All operational steps(finding java, parent dir, editing file,...) one solution
zFileProfile="/etc/profile"
zJavaHomePath=$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
echo $zJavaHomePath
echo "export JAVA_HOME=\"${zJavaHomePath}\"" >> $zFileProfile
echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> $zFileProfile
Result:
# tail -2 $zFileProfile
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"
export PATH=$PATH:$JAVA_HOME/bin
Explanation:
1) Let's break the full command into pieces
$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
2) Find java path from java command
# $(which java)
"/usr/bin/java"
3) Get relative path from symbolic path
# readlink -ze /usr/bin/java
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java"
4) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java
# readlink -ze /usr/bin/java | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin"
5) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/
# readlink -ze /usr/bin/java | xargs -0 dirname | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"