将 Java 系统退出值返回给 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18763849/
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
Return Java system exit value to bash script
提问by mike628
I am trying to get the return value from a java program ( System.exit(1);
) into a shell script, but it seems like its returning the jvm exit code, which is always 0, if it doesnt crash. For testing purposes, this is the very first line in my main().
Anyone know how to do this?
我试图将 java 程序 ( System.exit(1);
)的返回值获取到 shell 脚本中,但它似乎返回了 jvm 退出代码,如果它没有崩溃,它总是为 0。出于测试目的,这是我的 main() 中的第一行。有人知道怎么做吗?
My bash code:
我的 bash 代码:
....................
java bsc/cdisc/ImportData $p $e $t
#-----------------------------------------
# CATCH THE VALUE OF ${?} IN VARIABLE 'STATUS'
# STATUS="${?}"
# ---------------------------------------
STATUS="${?}"
# return to parent directory
cd ../scripts
echo "${STATUS}"
Thanks
谢谢
采纳答案by P.P
If your script has only the two lines then you are not checking for the correct exit code.
如果您的脚本只有这两行,那么您就没有检查正确的退出代码。
I am guessing you are doing something like:
我猜你正在做这样的事情:
$ java YourJavaBinary
$ ./script
where script contains only:
其中脚本仅包含:
STATUS="${?}"
echo "${STATUS}"
Here, the script
is executed in a subshell. So when you execute the script, $?
is the value of last command in that shell which is nothing in the subshell. Hence, it always returns 0
.
在这里,script
是在子shell 中执行的。因此,当您执行脚本时,$?
是该 shell 中最后一个命令的值,它在子 shell 中没有任何内容。因此,它总是返回0
。
What you probably wanted to do is to call the java binary in your script itself.
您可能想要做的是在脚本本身中调用 java 二进制文件。
java YourJavaBinary
STATUS="${?}"
echo "${STATUS}"
Or simply check the exit code directly without using the script:
或者直接检查退出代码而不使用脚本:
$ java YourJavaBinary ; echo $?
回答by Danilo Mu?oz
You should do like this:
你应该这样做:
Test.java:
测试.java:
public class Test{
public static void main (String[] args){
System.exit(2);
}
}
test.sh
测试文件
#!/bin/bash
java Test
STATUS=$?
echo $STATUS