javasundaram
javasundaram

Reputation: 967

How to call shellscript in java program?

How to call shellscript in java program?

String sCommandString="sh /home/admin/ping.sh";
Process p = Runtime.getRuntime().exec(sCommandString);

Upvotes: 3

Views: 92

Answers (3)

DemoUser
DemoUser

Reputation: 51

 Executing test.sh shellscript with passing param1 as parameter.Execute and wait for process to start and it will return int value 0 for successfully start of test.sh shellscript.

 Process process = null;
    try {
        int param1 =10;
        String[] command = {"sh", "-c", 'test.sh' + " " + param1};
        process = Runtime.getRuntime().exec(command);
        logger.debug("Process started for [param1 : " + param1 + "]);

        int i = process.waitFor();
        process.getOutputStream().close();

    } catch (Exception e) {
        logger.error("Error while creating process. Full stack trace is as follows ", e);
    } finally {
        try {
            if (process != null) {
                process.getInputStream().close();
            }
        } catch (Exception ex) {
            logger.error("Error while closing process. Full stack trace is as follows ", ex);
        }
    }

Upvotes: 0

Deepu--Java
Deepu--Java

Reputation: 3820

Pass the IP in command. I think this should work:

String sCommandString="sh /home/admin/ping.sh 10.12.12.26<Any IP>";

Upvotes: 1

Farvardin
Farvardin

Reputation: 5424

simplest way to run command and get ouput:

Process p = Runtime.getRuntime().exec("ls");
p.waitFor();
Scanner s = new Scanner(p.getInputStream());
while (s.hasNextLine()) {
    String l = s.nextLine();
    System.out.println(l);
}

Upvotes: 1

Related Questions