Running shell script from java code and pass arguments
Asked Answered
D

3

1

I am executing a shell script from Java program. I have implemented it using Runtime class. Below is the code I implemented

final StringBuilder sb = new StringBuilder("test.sh");
sb.append("/path to/my/text file");

final Process p = Runtime.getRuntime().exec(sb.toString());

Here sb is string buffer object where I append my parameters and use it in exec method. But the problem is the parameter I pass "/path to/my/text file" is considered as 4 parameters

/path
 to
/my/text
 file

But if run in shell as test.sh "/path to/my/text file" which is taken as single parameter. How can I achieve the same using Java code, where I need to consider this path with spaces as single argument. Any please will be really appreciable.

Define answered 10/10, 2012 at 5:12 Comment(0)
C
5

Use ProcessBuilder , it's what it's designed for, to make your life easier

ProcessBuilder pb = new ProcessBuilder("test.sh", "/path", "/my/text file");
Process p = pb.start();
Consumptive answered 10/10, 2012 at 5:25 Comment(2)
Why there are 2 arguments "/path" and "/my/text file" ? Shouldn't be new ProcessBuilder("test.sh", "/path to/my/text file")Define
No, each parameter MUST be separated, other wise they will send to the process as a single parameter, that's why the last parameter doesn't need to be escaped in quotesConsumptive
A
0

To recreate the command you run in shell manually, test.sh "/path to/my/text file", you will need to include the quotes.

final StringBuilder sb = new StringBuilder("test.sh");
sb.append(" \"/path to/my/text file\""); //notice escaped quotes
final Process p = Runtime.getRuntime().exec(sb.toString());
Alansen answered 10/10, 2012 at 5:16 Comment(0)
L
0

Your approach is correct you just need to add a space (" ") before parameters and escape the "/" and " " characters in the parameters

Lessor answered 10/10, 2012 at 5:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.