2

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!

1
  • 2
    That's because it's not being processed by a shell (i.e. bash). Use the array form of exec() and pass each argument as a separate string. Commented Aug 26, 2014 at 21:26

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.