Replace string matching to $JAVA_HOME in $PATH

75 views Asked by At

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'))
1

There are 1 answers

3
Grobu On

In your .bashrc, instead of using awk, you could resort to a few simple Unix commands like :

printf '%s' "$PATH" | tr ':' '\n' | grep -Fv '/java-' | paste -s -d ':'

So your export statements would look like this:

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="$(printf '%s' "$PATH" | tr ':' '\n' | grep -Fv '/java-' | paste -s -d ':'):$JAVA_HOME/bin"

Hope that helps.