X
X
xxxxc2018-07-26 10:13:07
Java
xxxxc, 2018-07-26 10:13:07

How to execute multiple bash commands at once in Java?

It turns out to execute only one command at a time. It's just that ls works as it should, but if you specify the path before, it doesn't work.

String[] cmd = {"/bin/bash", "-c", " echo  [password]| sudo -S cd / && ls"};
        Process pb = Runtime.getRuntime().exec(cmd);

Can anyone tell me how to run multiple commands?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-07-26
@sergey-gornostaev

Run one, check the return value, if successful, run the second. That is, to implement in the code exactly what the '&' symbol does.

D
Dmitry Alexandrov, 2018-07-26
@jamakasi666

In your case, Runtime.getRuntime().exec spawns as many as 3 different processes and each has its own environment.
You can read this and accordingly call bash once, get getInputStream() and getOutputStream() and then feed the necessary commands to the streams and read from them.
In general, I recommend looking towards ProcessBuilder, it is easier and more convenient with it.
Another option is to cheat, make a script in %temp%, execute it, delete this script after execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question