我必须从 shell 脚本运行可执行 jar 文件以获取字符串值。可执行 jar 无法返回值,因为 main 返回 void。我不能使用 System.exit(int),因为 jar 必须返回 String 类型的值。
请提出建议。
最佳答案
此数据应写入标准输出(Java 中的System.out
),并使用$(命令扩展)
捕获。
这是所有优秀的 Unix 公民(以及为数不多的 Java 程序)确保要做的事情:
- 将程序结果写入标准输出(System.out)
- 将错误信息和调试写入stderr (System.err)
- 使用
System.exit(0)
表示成功(如果没有使用 System.exit,这也是默认设置) - 使用
System.exit(1)
(或更高,最多 255)来指示失败
下面是演示 Java 和 shell 脚本之间相互作用的完整示例:
$ cat Foo.java
class Foo {
public static void main(String[] args) {
System.out.println("This data should be captured");
System.err.println("This is other unrelated data.");
System.exit(0);
}
}
一个非常基本的 list :
$ cat manifest
Main-Class: Foo
一个简单的shell脚本:
#!/bin/sh
if var=$(java -jar foo.jar)
then
echo "The program exited with success."
echo "Here's what it said: $var"
else
echo "The program failed with System.exit($?)"
echo "Look at the errors above. The failing output was: $var"
fi
现在让我们编译并构建 jar 并使脚本可执行:
$ javac Foo.java
$ jar cfm foo.jar manifest Foo.class
$ chmod +x myscript
现在运行它:
$ ./myscript
This is other unrelated data.
The program exited with success.
Here's what it said: This data should be captured
关于java - 如何构建可执行 jar 以将字符串返回给 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41580301/