Java – Open git bash on Windows and run commands in java

Open git bash on Windows and run commands in java… here is a solution to the problem.

Open git bash on Windows and run commands in java

I

use java on Windows and want to invoke Linux commands, so I try opening git bash and pasting some commands. I can open git bash, but I can’t paste anything.

This would open git bash:

String [] args = new String[] {"C:\\Progam Files\\Git\\git-bash.exe"}
Process proc = new ProcessBuilder(args).start();

When I do this, git bash opens but closes immediately :

String [] args = new String[] {"C:\\Progam Files\\Git\\git-bash.exe", "-c", "cd c:"}
Process proc = new ProcessBuilder(args).start();

Solution

You just need to change the path and git command.
But the git-bash output is printed in a separate .txt file because I can’t read it any other way.

public class GitBash {

public static final String path_bash = "C:/Program Files/Git/git-bash.exe";

 Create a file Output.txt where git-bash prints the results
    public static final String path_file_output_git_bash =
            "C:/Users/Utente/Documents/IntelliJ-DOC/IntelliJ_project/Prova/src/main/Git-bash/Output.txt";

public static void main(String[] args) {
         Path to your repository
        String path_repository = "cd C:/Users/Utente/Documents/Repository-SVN-Git/Bookkeeper";
         Git command you want to run
        String git_command = "git ls-files | grep .java | wc -l";

String command = path_repository + " && " + git_command + " > " + path_file_output_git_bash;

runCommand(command);
    }

public static void runCommand(String command) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command(path_bash, "-c", command);

Process process = processBuilder.start();

int exitVal = process.waitFor();
            if (exitVal == 0) {
                System.out.println(" --- Command run successfully");
                System.out.println(" --- Output = " + readFileTxt());

} else {
                System.out.println(" --- Command run unsuccessfully");
            }
        } catch (IOException | InterruptedException e) {
            System.out.println(" --- Interruption in RunCommand: " + e);
             Restore interrupted state
            Thread.currentThread().interrupt();
        }
    }

public static String readFileTxt() {
        String data = null;
        try {
            File myObj = new File(path_file_output_git_bash);
            Scanner myReader = new Scanner(myObj);
            while (myReader.hasNextLine()) {
                data = myReader.nextLine();
            }
            myReader.close();
        } catch (FileNotFoundException e) {
            System.out.println(" --- An error occurred");
            e.printStackTrace();
            }
            return data;
        }
    }
}

— Edit 2021/03/26 —

No .txt file is required to answer: Read output git-bash with ProcessBuilder in Java

Related Problems and Solutions