简体   繁体   中英

Run linux Script from Java

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?

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

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);
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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM