Linux 从 shell 脚本运行 jar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1592142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:47:19  来源:igfitidea点击:

Running a jar from shell script

javalinuxshellscriptingjar

提问by craftsman

I have a jar file named umar.jar in /root/umar/bin directory. I have a shell script file run.sh in same directory. Following is the content of run.sh

我在 /root/umar/bin 目录中有一个名为 umar.jar 的 jar 文件。我在同一目录中有一个 shell 脚本文件 run.sh。以下是run.sh的内容

#!/bin/bash
"$JAVA_HOME"/bin/java -jar /root/umar/bin/umar.jar

Now when I run the shell script, I get the following error

现在,当我运行 shell 脚本时,出现以下错误

Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file

After some googling, I found (as a folk from stackoverflow mentioned) that such errors occur when the Jar was compiled with a later version of the JDK than your JRE.

经过一些谷歌搜索,我发现(正如来自 stackoverflow 的一个人所提到的)当 Jar 是用比 JRE 更高版本的 JDK 编译时会发生这样的错误。

Now strange thing is, if I run this command directly on shell

现在奇怪的是,如果我直接在 shell 上运行这个命令

java -jar umar.jar

it works perfectly fine. If the jar was compiled with a later version of JDK than my JRE, it shouldn't have had run at all even from the shell.

它工作得很好。如果 jar 是用比我的 JRE 更高版本的 JDK 编译的,它甚至不应该从 shell 运行。

What do you suggest?

你有什么建议?

采纳答案by jqa

compare "java -version " and ""$JAVA_HOME"/bin/java -version"

比较 "java -version " 和 ""$JAVA_HOME"/bin/java -version"

You probably have multiple JVMs installed

您可能安装了多个 JVM

回答by denis.zhdanov

As already mentioned - you're trying to use byte code compiled by the later compiler with old jvm.

正如已经提到的 - 您正在尝试使用由旧 jvm 后期编译器编译的字节码。

Please note that if your PATHcontains multiple java executables of different versions you can switch between them easily using '-version'key.

请注意,如果您的PATH包含多个不同版本的 java 可执行文件,您可以使用“-version”键轻松地在它们之间切换。

Suppose you have java5 and java6 at your PATHand java5 is located before java6 there. You can see that java5 is used by default then (if you execute 'java -version'it prints corresponding information). However, you can start java6 easily using command like 'java -version:1.6 ...'(e.g. if you execute 'java -version:1.6 -version'you see that java6 is used).

假设您的PATH 中有 java5 和 java6,并且 java5 位于 java6 之前。您可以看到默认情况下使用 java5(如果您执行'java -version'它会打印相应的信息)。但是,您可以使用“java -version:1.6 ...”之命令轻松启动java6 (例如,如果您执行“java -version:1.6 -version”,您会看到使用了java6)。

回答by Andrew TR

Export the java and jre home which you need to use in your sh file.

导出您需要在 sh 文件中使用的 java 和 jre home。

Run the jar using the exported java home

使用导出的 java home 运行 jar

e.g

例如

export JAVA_HOME=/opt/java6
export JRE_HOME=/opt/java6/jre
/opt/java6/bin/java -Xms2048m -Xmx2048m -jar abc.jar