3

How to call shellscript in java program?

String sCommandString="sh /home/admin/ping.sh";
Process p = Runtime.getRuntime().exec(sCommandString);
4
  • here i want to check whether ip is reachable or not Commented Apr 28, 2014 at 9:37
  • so you need to pass an argument? Commented Apr 28, 2014 at 9:38
  • yes,i need to pass an argument paul Commented Apr 28, 2014 at 9:40
  • executed but no result shown .... Commented Apr 28, 2014 at 9:48

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

catch and print exception!
1

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

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

3 Comments

can you share your ping.sh?
#!/bin/bash ip=255.7.143.65 nmap -p 80 $ip if [ $? = 0 ] then echo "Port is Reachable" else echo "Port is not Reachable" fi
wait for 2 min, I will get back to you.
0
 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);
        }
    }

1 Comment

Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.