4

I'm using java on Windows, and want to call a Linux command so I'm trying to open git bash and paste some commands. I'm able to open git bash but can't paste anything.

This opens git bash fine:

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 right away:

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

3 Answers 3

4

You just have to change the paths and the git command. But the git-bash output is printed on a separate .txt file because I couldn't read it in 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 ---

Answer without the needs of a .txt file : Read output git-bash with ProcessBuilder in Java

Sign up to request clarification or add additional context in comments.

Comments

1

This will execute a bash script on Windows if you have Git installed without the need to write the output to a temp file.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringJoiner;

public class BashRunner
{
    public static final String BASH_PATH = "C:/Program Files/Git/bin/sh.exe";
    public static final String SCRIPT_NAME = "C:/temp/test-script.sh";

    public static void main(String[] args)
    {
        String output = runCommand(BASH_PATH, "-c", SCRIPT_NAME);
        System.out.println(output);
    }

    public static String runCommand(String... params)
    {
        ProcessBuilder pb = new ProcessBuilder(params);
        Process p;
        StringJoiner joiner = new StringJoiner(System.getProperty("line.separator"));
        try
        {
            p = pb.start();

            final BufferedReader reader = new BufferedReader(
                new InputStreamReader(p.getInputStream()));

            reader.lines().iterator().forEachRemaining(joiner::add);

            p.waitFor();
            p.destroy();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return joiner.toString();
    }
}

The contents of the script:

#!/bin/bash

echo "hello"
echo "world!"

Output:

hello
world!

Also, this will execute Git Bash silently in that you won't get a popup window while processing.

Comments

0

Do you need the bash terminal to pop up? If not, this could work

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("ls -aF");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}
    }
}

1 Comment

I do not need the terminal to pop up. I ran this and it gave me "CreateProcess error=2, The system cannot find the file specified". Also, since im using windows, wouldnt this run on the windows cmd?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.