HelloWorld
HelloWorld

Reputation: 17

Having problems running system commands from a java program:

This is giving just the output of ls:

String[] cmd={"bash","-c","ls","-l"}:  
ProcessBuilder pb=new ProcessBuilder(cmd);

Whereas this is giving long listing output properly:

String[] cmd={"bash","-c","ls -l"};

Upvotes: 0

Views: 109

Answers (3)

Edwin Buck
Edwin Buck

Reputation: 70959

String[] cmd={"bash","-c","ls -l"}:  
ProcessBuilder pb=new ProcessBuilder(cmd);

The arguements are to bash, so if you want bash to interpert your "command" via "bash", "-c", ... then the next item needs to be your entire command, aka "ls -l".

Bash will then parse up the "command" and the -l will be sent as a parameter to "ls". Currently it is a parameter to "bash", which is why you're not getting the results you desire.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363817

The former passes two option flags to bash: -c with argument ls, and -l which according to the manpage causes bash to act as a login shell.

The second passes one option flag, -c, which the argument ls -l as a single string.

Upvotes: 0

Martin Ellis
Martin Ellis

Reputation: 9651

In the first code snippet, the -l option is being passed as an argument to bash, and not to ls. Bash interprets the -l option as specifying that it should behave as a 'login' shell.

The argument after -c should include the whole bash script (spaces included) that you want to be executed, so the second code snippet is correct.

Upvotes: 2

Related Questions