How to pass the input value to shell script using java

久未见 提交于 2020-01-07 07:52:11

问题


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 ))"

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"

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

回答1:


from the examples :

    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();

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.

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.

Heres the interface for MyUserInfo : *click



来源:https://stackoverflow.com/questions/32605233/how-to-pass-the-input-value-to-shell-script-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!