I have a script that switches Java version in RHEL using alternatives --set java. However, I cannot export JAVA_HOME, CLASSPATH, or PATH from the same script for their use in the calling shell outside of the script. After calling the script, I need to source .bashrc which has the following.
export JAVA_HOME=$(dirname $(dirname $(readlink $(readlink $(which javac)))))
export CLASSPATH=.:$JAVA_HOME/jre/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME/bin
Here's the output I get at the prompt:
# $PATH
[tahamed@localhost ~]$ echo $PATH
/home/tahamed/.local/bin:/home/tahamed/bin:/sbin:/bin:/usr/bin:/usr/local/bin:/usr/local/sbin:/usr/sbin:/usr/lib/jvm/java-17-openjdk-17.0.10.0.7-2.el9.x86_64/bin:/usr/lib/jvm/java-17-openjdk-17.0.10.0.7-2.el9.x86_64/bin:/usr/lib/jvm/java-17-openjdk-17.0.10.0.7-2.el9.x86_64/bin
# $JAVA_HOME
[tahamed@localhost ~]$ echo $JAVA_HOME
/usr/lib/jvm/java-21-openjdk-21.0.2.0.13-1.el9.x86_64
The export PATH in it's current form will only append the new $JAVA_HOME/bin but what I really want to do is replace all occurrences of the substring matching $JAVA_HOME in the PATH before exporting.
I explored the following but getting "unterminated regexp" error on ']' in grep.
echo $PATH | awk '{gsub(/java-[^\/]*/, $(echo $JAVA_HOME | grep -o 'java-[^\/]*'))} 1'
[tahamed@localhost ~]$ echo $PATH | awk '{gsub(/java-[^\/]*/, $(echo $JAVA_HOME | grep -o 'java-[^\/]*'))} 1'
awk: cmd. line:1: {gsub(/java-[^\/]*/, $(echo $JAVA_HOME | grep -o java-[^/]*))} 1
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {gsub(/java-[^\/]*/, $(echo $JAVA_HOME | grep -o java-[^/]*))} 1
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {gsub(/java-[^\/]*/, $(echo $JAVA_HOME | grep -o java-[^/]*))} 1
awk: cmd. line:1: ^ unterminated regexp
grep works when run individually:
[tahamed@localhost ~]$ echo $JAVA_HOME | grep -o 'java-[^\/]*'
java-21-openjdk-21.0.2.0.13-1.el9.x86_64
When the above would work, I intend to update export PATH=... in .bashrc with the following.
export PATH=$(echo $PATH | awk '{gsub(/java-[^\/]*/, $(echo $JAVA_HOME | grep -o 'java-[^\/]*'))} 1'))
In your
.bashrc, instead of usingawk, you could resort to a few simple Unix commands like :So your
exportstatements would look like this:Hope that helps.