0

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"};
4
  • Running on Windows XP. If that matters. Thanks Commented Jan 27, 2012 at 16:17
  • I want to know why is it not giving the output for the first way i have mentioned.The output should be a long listing. Commented Jan 27, 2012 at 16:18
  • The first example, you are using bash to parse the command line. Try { "ls", "-l" } Commented Jan 27, 2012 at 16:21
  • Oh okay. Thank you. But what if I want to dynamically display files using cat command. An example scenario would be when I want to pass file names in a loop for display. Commented Jan 27, 2012 at 16:26

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh okay. Thank you. But what if I want to dynamically display files using cat command. An example scenario would be when I want to pass file names in a loop for display.
If you want to invoke cat once with multiple parameters, then you could use a StringBuilder and for loop to build up the command line into a single string (with spaces between file names). That could be appended onto the string "cat ", and used for the command line argument following -c.
0

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.

1 Comment

Oh okay. Thank you. But what if I want to dynamically display files using cat command. An example scenario would be when I want to pass file names in a loop for display
0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.