我想从shell脚本运行一个Java程序。所以我做了类似下面的事情
我的测试Java文件如下
public class EchoTest {
public static void main (String args[]) {
System.out.println ("scuccess ..!!");
}
我的测试shell脚本文件如下
out=$(java EchoTest)
echo $out
我编译了java程序,然后我运行了那个shell脚本(比如$ sh Myscript.sh)。现在它将输出打印到console.Upto现在它正常工作。
如果我写下面的程序(引发一些例外)
public class EchoTest {
public static void main (String args[]) {
System.out.println ("Value is "+(2/0));
}
它只是将java异常打印到控制台上。但我的要求是我希望它在控制台上打印0或1,即当我的java程序失败时我希望得到0(零)并且想要在java程序成功执行时得到1(一)。
答案 0 :(得分:5)
The documentation from the java program says :
EXIT STATUS
The following exit values are generally returned by the launcher, typically when the launcher is called with the wrong arguments, serious errors, or exceptions thrown from the Java Virtual Machine. However, a Java application may choose to return any value using the API call System.exit(exitValue).
So if you do not do anything, the JVM follows the common convention of returning a 0 value to the caller on successfull completion and a non null value in case of error.
Your shell script should then be :
java EchoTest
if [ $? -eq 0]
then echo 1
else echo 0
fi
That means that you can ignore standard output and standard error and just rely on the exit status from the JVM.
As suggested by @alk, you can even replace first line with out = $( java EchoTest )
and use $out
in the success branch (when $?
is 0
)
答案 1 :(得分:4)
如果您检测到错误/异常,则需要将System.exit(code)
与您想要的代码一起使用
你会有
System.exit(0) // if you detect error, you need to handle exception
System.exit(1) // when no error
答案 2 :(得分:1)
从shell处理程序的更完整示例可能是
#!/bin/bash
#
# run.sh command
#
# Runs command and logs the outcome to log.<pid> and err.<pid>.
#
cmd=${1}
# Run cmd and log standard output (1) to log.<pid> and standard error (2) to err.<pid>.
$cmd 1>log.$$ 2>err.$$
# Copy the return code from cmd into result.
result=$?
# Test whether result is 0.
if [ $result -eq 0 ]; then
echo "$cmd" succeeded.
cat log.$$
else
echo "$cmd" failed with result = $result!
cat err.$$
fi
exit $result
# eof
$$
评估shell的pid,因此代码可以与其自身的副本并行运行。
像这样调用上面的脚本
$ run.sh "java myprogram"
答案 3 :(得分:0)
非常感谢你的回复。 我得到了以下脚本的解决方案,但我不知道这里发生了什么, 请告诉我这里发生了什么。
cmd="java EchoTest"
$cmd >log.$$ 2>err.$$
result=$?
if [ $result -eq 0 ]; then
echo "1"
else
echo "0"
#echo $result
fi
rm log.$$ >/dev/null
rm err.$$ >/dev/null