Reputation: 1609
I need to execute Linux command like this using Runtime.getRuntime().exec() :
/opt/ie/bin/targets --a '10.1.1.219 10.1.1.36 10.1.1.37'
Basically, this command is to connect each targets to server one by one (10.1.1.219, 10.1.1.36, 10.1.1.37). It works well in terminal, the result should be :
['10.1.1.219', '10.1.1.36', '10.1.1.37']
But if I execute the command using Runtime.getRuntime().exec(execute), like this :
execute = "/opt/ie/bin/targets" + " " + "--a" + " " + "'" + sb
+ "'";
Java will treat the single quote as string to execute, the result will be :
callProcessWithInput executeThis=/opt/ie/bin/targets --a '10.1.1.219 10.1.1.36 10.1.1.37'
The output for removing undesired targets :["'10.1.1.219"]
Anyone knows how to solve it? Thanks!
Upvotes: 2
Views: 1970
Reputation: 34591
Quote characters are interpreted by the shell, to control how it splits up the command line into a list of arguments. But when you call exec
from Java, you're not using a shell; you're invoking the program directly. When you pass a single String
to exec
, it's split up into command arguments using a StringTokenizer
, which just splits on whitespace and doesn't give any special meaning to quotes.
If you want more control over the arguments passed to the program, call one of the versions of exec
that takes a String[]
parameter. This skips the StringTokenizer
step and lets you specify the exact argument list that the called program should receive. For example:
String[] cmdarray = { "/opt/ie/bin/targets", "--a", "10.1.1.219 10.1.1.36 10.1.1.37" };
Runtime.getRuntime().exec(cmdarray);
Upvotes: 7