Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (5.6k points)

I'm trying to run AWS commands within Java code, I tried to run the bash command in java but I wonder it doesn't show anything. And just gives "Exited with error code: 2". When I just run "aws ls help" in bash it works. I'm not getting what is the problem and how can I resolve 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();

                }

        }

}

1 Answer

0 votes
by (12.4k points)

Java code is completely fine, you just replace the "command" with 

"processBuilder.command("bash", "-c", "echo 1 2 3");"

The problem can be fixed by

"processBuilder.command("bash", "-c", "/usr/bin/aws ls help 2>&1; true");"

Interested to know about AWS? Come & join AWS Training provided by Intellipaat.

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
0 answers
+1 vote
1 answer

Browse Categories

...