1

I'm trying to run bash from Java on Windows (here with the Windows Linux Subsystem, but Git Bash is the same), but even the basics are failing:

bash --noprofile --norc -c 'echo $PWD'`

In cmd.exe this works fine:

Works fine in CMD.exe

In java:

import static java.util.stream.Collectors.joining;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;

public class ProcessBuilderTest {
    public static int runBatch() {
        List<String> commandLine = new ArrayList<>();
        // both following lines have the same result
        commandLine.add("bash");
        // commandLine.add("C:\\Windows\\System32\\bash.exe"); 

        commandLine.add("--noprofile");
        commandLine.add("--norc");
        commandLine.add("-c");
        commandLine.add("'echo $PWD'");

        System.out.println("cmd: " + commandLine.stream().collect(joining(" ")));
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
            Process process = processBuilder
                .redirectErrorStream(true)
                .start();
            new BufferedReader(new InputStreamReader(process.getInputStream())).lines()
                .forEach(System.out::println);
            return process.waitFor();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (InterruptedException e) { // NOSONAR
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        runBatch();
    }
}

Running the above results in the following, and the process never exits.

cmd: bash --noprofile --norc -c 'echo $PWD'
/bin/bash: echo /mnt/c/scratch/pbtest: No such file or directory

Expected behavoir: no error and the process terminates.

2 Answers 2

1

bash is running in cmd.exe in your windows environment

Could you have java running the following command instead ?

cmd.exe /c bash --noprofile --norc -c 'echo $PWD'

ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", 
    "/c", 
    "bash --noprofile --norc -c 'echo $PWD'");

or with the List as you initially tried

Inspired by mkyong post

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

2 Comments

Worth a try, but unfortunately it has the same result.
I have just edited my post. Hopefully it should work now. I don't have a window machine to test it though...
1

Using Git-bash: I changed these two lines and ir ran as expected:

// Used full path to the underlying bash.exe shell
commandLine.add("\"C:\\Program Files\\Git\\bin\\bash.exe\"");

// Removed quotes
commandLine.add("echo $PWD"); 

Ref: https://superuser.com/a/1321240/795145

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.