简体   繁体   中英

Problems in running AWS CLI bash command within Java

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();
                }
        }
}

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

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