使java程序返回值来调用shell脚本 [英] Make java program return value to calling shell script

查看:43
本文介绍了使java程序返回值来调用shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Unix 大师!

我有一个 Java 程序,它将一些参数传递给 Servlet.Servlet 将信息输入到数据库中,并将创建的行的 ID 返回给调用它的 java 程序.Java 程序在 Unix shell 脚本中运行,该脚本随后调用另一个 Java 程序 Java Program_2(比如说).

I have a Java program which passes some parameters to a Servlet. The Servlet enters the info into a DB and returns back the ID of a row created back to the java program that calls it. The Java program is run in a Unix shell script, which later goes on to call another java program Java Program_2 (say).

我的问题是 - 我需要将我们从 Java Program 获得的 ID 作为参数传递给同一个 shell 中的 Java Program_2脚本.是否有任何最佳做法?

My issue is this - I need to pass the ID we get from Java Program as a parameter to Java Program_2 in that same shell script. ARe there any best practice for this?

目前我正在做的事情 -

1) 使用 System.exit() 使 java 程序返回退出代码.与此有关的 2 个问题 - 如何在 shell 中的变量中捕获退出代码?这是正确的方法吗?退出代码实际上是为了返回程序的成功参数...

1) Make the java program return an exit code with System.exit(). 2 questions with this - How do i catch the exit code in a variable in the shell? Is this the right way to do it? Exit code is actually meant for returning the success parameter of the program...

2) 将输出写入文件 java Java_Program >opt.txt.如果我这样做,那么如何再次读取shell变量中opt.txt的内容?

2) Write the output in a file java Java_Program >opt.txt. If I do this, then how do I read the contents of opt.txt in a shell variable again?

非常感谢!

实际上我应该在此之前提到这一点...程序在不同的机器上.我使用脚本通过 ssh 连接到另一台机器..然后运行 ​​java 程序 2.因此,我无法通过管道连接两者.

I should have mentioned this before actually... the programs are in different machines. I ssh into the other machine using the script..and then run java program 2. Hence, I cannot pipe the two.

推荐答案

我不建议使用退出状态来携带数据,原因你已经说了.捕获退出状态取决于您使用的 shell,但在 Bash 中,特殊的 $? 变量包含最后执行的进程的退出状态.

I would not recommend using the exit status to carry data, for the reasons you've stated. Catching the exit status depends on what shell you're using, but in Bash, the special $? variable contains the exit status of the last process executed.

将数据写入标准输出更为惯用.在 Bash 中,您可以按如下方式捕获它:

Writing data to stdout is far more idiomatic. In Bash, you capture it as follows:

output=$(java Java_Program)

或:

output=`java Java_Program`

(您经常会听到有人认为首选第一种语法.)

(You will often hear arguments that the first syntax is to be preferred.)

然后,您可以将其提供给下一个流程的标准输入:

You can then feed this to stdin of your next process with:

echo $output > java Java_Program_2

更简单地说,您可以简单地将您的流程连接在一起:

More simply, you can simply pipe your processes together:

java Java_Program | java Java_Program_2

这篇关于使java程序返回值来调用shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆