In Java, how do I execute a linux program with options, like this:
ls -a
(the option is -a),and another:
./myscript name=john age=24
I know how to execute a command, but cannot do the option.
Asked
Active
Viewed 1,495 times
1
-
1So which API are you using to execute the command? – Neil Aug 09 '12 at 23:35
-
http://www.gnu.org/software/gnuprologjava/api/gnu/getopt/Getopt.html looks promising – Dennis Meng Aug 09 '12 at 23:54
-
There are SO many options... :-/ – Richard Sitze Aug 10 '12 at 01:04
-
possible duplicate of [Linux commands from Java](http://stackoverflow.com/questions/126116/linux-commands-from-java) – Alex K Aug 10 '12 at 13:42
2 Answers
2
You need to execute an external process, take a look at ProcessBuilder and just because it almost answers your question, Using ProcessBuilder to Make System Calls
UPDATED with Example
I ripped this straight from the list example and modified it so I could test on my PC and it runs fine
private static void copy(InputStream in, OutputStream out) throws IOException {
while (true) {
int c = in.read();
if (c == -1) {
break;
}
out.write((char) c);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
// if (args.length == 0) {
// System.out.println("You must supply at least one argument.");
// return;
// }
args = new String[] {"cmd", "/c", "dir", "C:\\"};
ProcessBuilder processBuilder = new ProcessBuilder(args);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
copy(process.getInputStream(), System.out);
process.waitFor();
System.out.println("Exit Status : " + process.exitValue());
}

MadProgrammer
- 343,457
- 22
- 230
- 366
-
I am aware if ProcessBuilder, but kinda struggling with it. Any concrete example? How would you set the String array in the contructor of ProcessBuilder? `ProcessBuilder pb = new ProcessBuilder(.......)` How to I set command and args inside the dot dot dot? – Simo Aug 09 '12 at 23:39
-
I'd have a read of the example, it literally does what you want. `ProcessBuilder` takes either a `List
` or array of `String` arguments, the first is the command to be executed, the remainder at the command parameters (each one should be a separate parameter) – MadProgrammer Aug 09 '12 at 23:45 -
You might also like to have a read of http://stackoverflow.com/questions/1410741/want-to-invoke-a-linux-shell-command-from-java for executing shell commands – MadProgrammer Aug 09 '12 at 23:46
1
Apache Commons has a library built to handle this type of thing. I wish I knew about it before I coded something like this by hand. I found it later on. It takes options in various formats for a command line program.

Logan
- 2,369
- 19
- 20