Michael Zakariaie
Michael Zakariaie

Reputation: 185

Back to back commands in mac terminal via java Runtime

Basically I have 2 commands I need to execute via a java program the way you would if you were just typing it into terminal.

so like

cd /Users/nameOfUser/Desktop/someFolder/someSubFolder

and then another command I want to execute within that directory. Currently I am doing this:

Process navigate = Runtime.getRuntime().exec("cd /Users/nameOfUser/Desktop/someFolder/someSubFolder");
Process doSomething = Runtime.getRuntime().exec("commandInThatDirectory");

Which doesn't work, it doesn't throw an exception but the second process doesn't seem to take place in the directory specified before it. I am new to processes and runtimes so please bear with me :P.

Is their a way to execute the commands back to back within the same instance of terminal or at least a format for 1 command where you can specify the directory for another command to take place in? I'm a linux user so I don't know mac terminal very well sorry.

Upvotes: 1

Views: 224

Answers (1)

Deendayal Garg
Deendayal Garg

Reputation: 5148

It can be done something like this. you can run any command by by placing a semicolon between the commands.

public class Main {
public static void main(String[] args) throws IOException {

        ProcessBuilder pb1 = new ProcessBuilder(
                "bash",
                "-c",
                "cd /Users/nameOfUser/Desktop/someFolder/someSubFolder;commandInThatDirectory");
        pb1.redirectErrorStream(true);
        Process p = pb1.start();
    }
}

Upvotes: 1

Related Questions