user3846091
user3846091

Reputation: 1703

Unable to send parameters to bash script from java

I am trying to run a bash script on my Ubuntu machine through Java. The bash script takes 2 input as parameters that i am passing as an array However, it does not seem to be passing the value of array[0] and array[1] to the bash script?

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.omg.CORBA.portable.InputStream;

public class readBashScript {

    public static void readBashScript() {
        try {

            String[] array = {"ys1","R"};

            Process proc = Runtime.getRuntime().exec("var/www/red/marsh_webreset.sh /",array); 
            BufferedReader read = new BufferedReader(new InputStreamReader(
                    proc.getInputStream()));
            try {
                proc.waitFor();
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
            while (read.ready()) {
                System.out.println(read.readLine());
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Upvotes: 3

Views: 527

Answers (4)

mkazma
mkazma

Reputation: 582

You should send each value of the array at a time. You can't send the array as it is as an argument to the bash script since it can't extract the values by itself.

Process proc = Runtime.getRuntime().exec("/var/www/redbutton/marsh_webreset.sh "+array[0]+" "+ array[1]+" /");

Upvotes: 0

proulxs
proulxs

Reputation: 508

Take a look at some documentation.

The second argument you are passing to the exec method is:

envp -- array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

I recommend taking a look at this and this.

If you want to pass environment variables, you can add them as an array but has to be in format "key=value".

IE:

$ ONE=1 TWO=2 shell.sh

You can then echo these variables in your shell script.

$ echo $ONE

Upvotes: 2

Marsh
Marsh

Reputation: 417

You are passing the arguments incorrectly Try below code:

Process proc = Runtime.getRuntime().exec("/var/www/redbutton/marsh_webreset.sh "+array[0]+" "+ array[1]+" /");

Upvotes: 1

dimo414
dimo414

Reputation: 48794

It looks like you are calling the wrong Runtime.exec() method. You're passing in a command and an array of environment variables, but you want to pass in arguments to the process you're executing. Instead of exec(String, String[]) you want to call exec(String[]).

You likely want to look at the error stream as well - it probably has an informative error message. Additionally, I'm not sure that / at the end of the command string is helpful, or even valid. You probably also don't want to import org.omg.CORBA.portable.InputStream.

Upvotes: 0

Related Questions