替换 $PATH 中与 $JAVA_HOME 匹配的字符串

问题描述 投票:0回答:1

我有一个脚本,可以使用替代方案 --set java 在 RHEL 中切换 Java 版本。但是,我无法从同一脚本导出 JAVA_HOME、CLASSPATH 或 PATH 以便在脚本外部的调用 shell 中使用。调用脚本后,我需要“source .bashrc”,其中包含以下内容。

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

# $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 to $JAVA_HOME in the PATH before exporting. 

I explored the following but getting "unterminated regexp" error on ']' in grep. 

回显$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 .bashrc export PATH=... with the following. 

导出 PATH=$(echo $PATH | awk '{gsub(/java-[^/]/, $(echo $JAVA_HOME | grep -o 'java-[^/]'))} 1'))


Help!!
awk path grep gsub java-home
1个回答
0
投票

在您的

.bashrc
中,您可以使用一些简单的 Unix 命令,例如:
,而不是使用 
awk

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

所以你的

export
陈述将如下所示:

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"

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.