1

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.

1 Answer 1

1

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

1 Comment

thank you, what is the "-c" for though? I understand bash tells it to open/use terminal but what does that c part do?

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.