Reputation: 1
I'm trying to run an AWS command within Java code (in Linux). Like always, I try to run the bash command like this in Java. But I wonder it doesn't show anything. And just prints Exited with error code : 2
. When I just run aws ls help
in bash, it works.
What is the problem? How to solve it?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestCMD {
public static void main(String[] args) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", "aws ls help");
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 844
Reputation: 20022
The Java code is not the problem. It works fine, what you can check by replacing the command
with
processBuilder.command("bash", "-c", "echo 1 2 3");
You have 2 "problems".
The first problem is that aws
writes its output to stderr, not stdout.
The second problem is that aws
returns 2 where 0
would be IMHO better.
You can test this on the commandline with:
aws ls help 2>/dev/null; echo $?
The problems can be fixed with
processBuilder.command("bash", "-c", "/usr/bin/aws ls help 2>&1; true");
Upvotes: 1