1

I have the following java code

ArrayList<String> argList = new ArrayList<>();
argList.add("Hello");
argList.add("World");
String[] args = argList.toArray(new String[argList.size()]);

Process p =Runtime.getRuntime().exec("echo '$1 $2' ", args);

result is $1 $2 but i want to print Hello World. Can anybody help me?

2
  • Is it your real code because in this example you are executing args not argList. Commented Aug 31, 2013 at 8:15
  • @ user2699859 : The single quotes escapes the $. Commented Aug 31, 2013 at 8:20

4 Answers 4

3

Create a shell to use the parameter expansion:

ArrayList<String> command = new ArrayList<>();
command.add("bash");
command.add("-c");
command.add("echo \"$0\" \"$1\"");
command.addAll(argList);

Process p = Runtime.getRuntime().exec(command.toArray(new String[1]));

Output:

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

Comments

1

You should use the exec(String[] args) method, instead:

    String[] cmdArgs = { "echo", "Hello", "World!" };
    Process process = Runtime.getRuntime().exec(cmdArgs);
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }

The problem is, that the first argument in the exec() method is not the script, but the name of the script.

If you want to use variables, like $1 and $2 you should do that in your script.

So, what you actually might want is:

    String[] cmdArgs = { "myscript", "Hello", "World!" };
    Process process = Runtime.getRuntime().exec(cmdArgs);

Comments

1
ArrayList<String> argList = new ArrayList<>();
argList.add("echo");
argList.add("Hello");
argList.add("World");

Process p =Runtime.getRuntime().exec(args);

This way the String[] will be passed as an argument to echo.

If you want to use $ then you will have to write a shell script.

Comments

1

Echo will print all arguments as such. In your case '$1 $2' is interpreted as normal string.. Since it will anyway print all args you could use some thing like below.

  ProcessBuilder pb= new ProcessBuilder().command("/bin/echo.exe", "hello", "world\n");

Another option is co create a small script say mycommands.sh with appropriate contents

   echo $@ 
   echo $1 $2  
   #any such

You then invoke your script... like

  ProcessBuilder pb= new ProcessBuilder().command("/bin/bash" , "-c", "<path to script > ", "hello", "world\n");

Note the use of ProcessBuilder. This is an improved api instead of Runtime.(especially for quoting etc)

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.