如何构建可执行JAR以将字符串返回到外壳脚本 [英] how to build Executable jar to return string to shell script
本文介绍了如何构建可执行JAR以将字符串返回到外壳脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请提出建议。
推荐答案
此数据应写入标准输出(在JAVA中为System.out
),并使用$(command expansion)
捕获。
以下是所有优秀的Unix公民(以及太少的Java程序)应该确保做的事情:
- 将程序结果写入标准输出(System.out)
- 将错误消息和调试写入stderr(System.err)
- 使用
System.exit(0)
表示成功(如果未使用System.exit,这也是默认设置) - 使用
System.exit(1)
(或更高,最多255)表示失败
这里有一个完整的示例来演示Java和外壳脚本之间的相互作用:
$ 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);
}
}
一个非常基本的清单:
$ cat manifest
Main-Class: Foo
一个简单的外壳脚本:
#!/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
这篇关于如何构建可执行JAR以将字符串返回到外壳脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文