Runtime.getRuntime().exec not working with gcloud

510 views Asked by At

I am trying to describe the last executed dataflow job to check whether a specific dataflow job is running, stopped, failed, or executing using java.

I am trying to execute gcloud command using Runtime.getRuntime().exec(command)

String command ="gcloud dataflow jobs describe $(gcloud dataflow jobs list --sort-by=CREATION_TIME --limit=1 --format=\"get(id)\") --format=json";
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec(command);
BufferedReader is = new BufferedReader(new
InputStreamReader(process.getInputStream()));

When I am executing this code I am getting an error as:

Exception in thread "main" java.io.IOException: Cannot run program "gcloud": CreateProcess error=2, The system cannot find the file specified

Can someone help me out here to resolve this error?

1

There are 1 answers

2
rzwitserloot On BEST ANSWER

The Process and ProcessBuilder classes launches processes.

It does not run bash shell commands, but that's what you typed. You can't run this.

What you can try to do is start bash, and pass this as the command for bash to execute. Don't use runtime.exec, use ProcessBuilder, don't pass the command as a single string, pass each argument as a separate string. Try:

List.of("/bin/bash", "-c", "gcloud... all that mess"); as command.

I'm not even sure if that $( stuff is bash or zsh or fish or whatnot, make sure you start the right shell.