Sunday, October 11, 2015

Executing OSX terminal commands from Java

Couple days ago I've faced a situation when I needed to execute a pipeline of commands in OSX terminal from Java code and return result into program itself. You may say that there's a lot of information in the Internet (as a lot of us would say) but after spending some time it went out that those solutions are a bit incomplete for me :) So I'll add some information for those who might need that.

Problem:
- execute command in OSX terminal from Java program and return result from terminal back to the program;

Solution:

public static void main(String[] args) 
                             throws IOException, InterruptedException {
   try {
        Runtime runtime = Runtime.getRuntime();
        String[] cmd = {"/bin/bash", "-c", "Your command goes here"};

        Process process = runtime.exec(cmd);

        BufferedReader input = 
           new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;

        while ((line = input.readLine()) != null) {
                System.out.println(line);
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        e.printStackTrace();
    }
}

And it's simply all. So You might want to create some kind of service class for that command creation and then simply pass it to runtime executor - it's up to You.

Before the end just one more important detail:

Problem:
- execute pipeline of commands (where we need to execute 2 or more) and only after that return a result back to the program

Solution:
- here I'll show an example of such pipeline:

"cd /Users/Projects/Test && git checkout master && git checkout -b master-test && git log"

So You can add as many of Your commands as You need just separate those with && and that will work.

That's probably all for that topic.

No comments:

Post a Comment