0

I want to execute this command through java

"docker ps -q | xargs docker inspect --format '{{.HostConfig.NetworkMode}} {{ .Config.Image }} {{ .NetworkSettings.IPAddress }}'"

when I try to execute this command through java, I'm unable to get any output. I'm not getting any error or exception.

Below the code

String command ="docker ps -q | xargs docker inspect --format '{{.HostConfig.NetworkMode}} {{ .Config.Image }} {{ .NetworkSettings.IPAddress }}'";

process = Runtime.getRuntime().exec(command);
bufferedReaderObj = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    while ((sLine = bufferedReaderObj.readLine()) != null) {
}

Please help me, I think it is because of curly braces in command.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You may also want to check what `getErrorStream()` contains . – Arnaud Feb 27 '20 at 15:38
  • 1
    Does this answer your question? [Why does Runtime.exec(String) work for some but not all commands?](https://stackoverflow.com/questions/31776546/why-does-runtime-execstring-work-for-some-but-not-all-commands). `|` and `'..'` are shell features, so you will need to invoke it via a shell (the curly braces don't affect anything) – that other guy Feb 27 '20 at 21:32

1 Answers1

0

The issue is not with the curly braces in the command. Try to make it run as a shell script than a simple command.

Runtime.getRuntime() retrieves the current Java Runtime Environment. And with exec(String [] cmdArray) method, commands are passed to os-specific function calls, which creates an os-specific process or known as running program. A shell script is a the way to issue os specific commands, in this case docker ps and docker inspect.

String[] cmd =
        {"/bin/sh",
                "-c",
                "docker ps -q | xargs docker inspect --format '{{.HostConfig.NetworkMode}} {{ .Config.Image }} {{ .NetworkSettings.IPAddress }}'"};

Process process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReaderObj = new BufferedReader(new InputStreamReader(process.getInputStream()));
String sLine = "";
StringBuilder output = new StringBuilder();
while ((sLine = bufferedReaderObj.readLine()) != null) {
    output.append(sLine);
}
System.out.println(output);

wpnpeiris
  • 766
  • 4
  • 14
  • I tried running it as a shell script and still no output. Any idea what the problem could be? I'm trying to run "docker ps -q" command. Thanks! – Evya2005 May 24 '21 at 20:15