Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

It is quite simple to run a Unix command from java.

Runtime.getRuntime().exec(myCommand);

But is it possible to run a Unix shell script from java code? If yes, would it be a good practice to run a shell script from within java code?

share|improve this question
1  
Things get interesting if that shell script is interactive. –  ernesto Apr 18 at 10:57

10 Answers 10

You should really look at Process Builder. It is really built for this kind of thing.

ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 Process p = pb.start();
share|improve this answer

I would say that it is not in the spirit of Java to run a shell script from Java. Java is meant to be cross platform, and running a shell script would limit its use to just UNIX.

With that said, it's definitely possible to run a shell script from within Java. You'd use exactly the same syntax you listed (I haven't tried it myself, but try executing the shell script directly, and if that doesn't work, execute the shell itself, passing the script in as a command line parameter).

share|improve this answer
10  
Yes, but in many ways that "spirit of Java" or "write once run everywhere" mantra is a myth anyway. –  BobbyShaftoe Feb 8 '09 at 5:51
9  
What's mythical about it? –  Chris Ballance Feb 8 '09 at 5:57
2  
"write once run everywhere" is up to the programmer... –  Spider Sep 29 '11 at 19:31
7  
what's mythical about it is, that you usually end up writing numerous switches and if statements to get around all of the nuances that don't work exactly the same on different platforms despite the best efforts of the people who came up with the java core libraries. –  Brian Sweeney Nov 17 '11 at 19:32
    
Surprisingly enough! I agree with all the comments above and the answer! –  Annjawn Nov 21 '12 at 23:00

I think you have answered your own question with

Runtime.getRuntime().exec(myShellScript);

As to whether it is good practice... what are you trying to do with a shell script that you cannot do with Java?

share|improve this answer

You can use Apache Commons exec library also.

Example :

package testShellScript;

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class TestScript {
    int iExitValue;
    String sCommandString;

    public void runScript(String command){
        sCommandString = command;
        CommandLine oCmdLine = CommandLine.parse(sCommandString);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            // TODO Auto-generated catch block
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.err.println("permission denied.");
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        TestScript testScript = new TestScript();
        testScript.runScript("sh /root/Desktop/testScript.sh");
    }
}

For further reference, An example is given on Apache Doc also.

share|improve this answer
    
Can I run this in Windows? –  akb Apr 4 at 18:01
    
@akb can you explain more ? –  KisHan SarsecHa Gajjar Apr 9 at 10:59

Yes it is possible to do so. This worked out for me.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.omg.CORBA.portable.InputStream;

public static void readBashScript() {
        try {
            Process proc = Runtime.getRuntime().exec("/home/destino/workspace/JavaProject/listing.sh /"); //Whatever you want to execute
            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());
        }
    }
share|improve this answer

I think with

System.getProperty("os.name"); 

Checking the operating system on can manage the shell/bash scrips if such are supported. if there is need to make the code portable.

share|improve this answer

As for me all things must be simple. For running script just need to execute

new ProcessBuilder("pathToYourShellScript").start();
share|improve this answer

It is possible, just exec it as any other program. Just make sure your script has the proper #! (she-bang) line as the first line of the script, and make sure there are execute permissions on the file.

For example, if it is a bash script put #!/bin/bash at the top of the script, also chmod +x .

Also as for if it's good practice, no it's not, especially for Java, but if it saves you a lot of time porting a large script over, and you're not getting paid extra to do it ;) save your time, exec the script, and put the porting to Java on your long-term todo list.

share|improve this answer

Just the same thing that Solaris 5.10 it works like this ./batchstart.sh there is a trick I don´t know if your OS accept it use \\. batchstart.sh instead. This double slash may help.

share|improve this answer

But make sure that jdk version in which you compiled your application and the jdk version installed in your unix/linux should be same.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.