如何使用Java将输入值传递给Shell脚本 [英] How to pass the input value to shell script using java
问题描述
我已经创建了shell脚本来添加两个数字.我想从Java执行该Shell脚本,而我正在使用Jsch库.你能帮我这个忙吗?
I have created the shell script to add two numbers. I want to execute that shell script from java and I am using Jsch library. Can you please help me on this.
first_num=0
second_num=0
echo -n "Enter the first number-->"
read first_num
echo -n "Enter the second number-->"
read second_num
echo "first number + second number = $ (( first_num + second_num ))"
是的.我已经在"Jsch"站点中检查了示例,但是我无法将输入内容输入到Shell脚本中.
Yes. I have checked examples in "Jsch" sites, But i am not able to enter the input to shell script.
我按照你说的尝试过.请参见以下代码
I tried as you said. Please see the following piece of code
String command = "bash /home/opt/addtwonumber.sh 1 2"
我更改了下面提到的shell脚本
And I changed the shell script mentioned below
$first_num
$second_num
echo "first number + second number = $ (( first_num + second_num ))"
但是它不起作用.我得到类似的结果
But it doesn't work. i am getting the results like
first_number + second_number = 0
推荐答案
示例:
String user = "USERNAME";
host = "HOSTNAME";
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Session session=jsch.getSession(user, host, 22);
String command = "YOUR_SCRIPTFILE_HERE PARAMETER_ONE PARAMETER_TWO";
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (in.available() > 0)
continue;
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
提醒您:切勿在任何可用于生产的代码中使用while(true)
,多数民众赞成在...不好的代码,无论您捕获多少异常,它都会在某些时候中断/生成死锁,无论您多久插入一次break
这样的语句-都会发生.
Mind you : never use while(true)
in any production-ready code, thats just ... bad code and it will break / generate deadlocks at some point, no matter how many exceptions you catch, no matter how often you insert statements like break
- it will happen.
因此,您所需要做的就是将参数立即放在脚本文件之后,并且应该就此放置它-但仅适用于命令行参数,AFAIK在脚本运行时不容易输入参数-read
将不起作用为您服务,因为您的脚本显然不是本地的.您不能使用需要本地输入的脚本,而需要切换到命令行参数-即$1
,$2
等.
So all you need to do is place your parameters immediately after your scriptfile and that should be about it - but that only works with commandline parameters, AFAIK it isnt easily possible to input parameters during script runtime - read
will not work for you as your script apparently isnt local. You cant use scripts which require local input, you need to switch to commandline parameters - namely $1
, $2
and so on.
此处显示MyUserInfo
的界面: *单击
这篇关于如何使用Java将输入值传递给Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!