I'm trying to run shell script thru Java in Mac OS. The shell script has git clone command clone a repository.
I have tried using process builder API. It's not giving any exception though but the repo is not cloning when I run the code.
public class Test {
public static void main(String[] args) throws IOException {
Process p;
try {
List<String> cmdList = new ArrayList<String>();
cmdList.add("/Users/Folder/AnotherFolder/Another/Final/clone.sh");
ProcessBuilder pb = new ProcessBuilder(cmdList);
p = pb.start();
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
Expecting to clone git project in the path, but not giving any output or Exception.
2 Answers 2
Above JAVA code works fine, I suspect there could be some issue with the script.Because git local repo will not be know when java program tries to execute the shell script.
On executing program with below script git clone works fine.
#!/bin/bash
mkdir ~/repo
cd ~/repo
git init
#git config user.email "email"
#git config user.name "user"
/usr/local/bin/git clone https://github.com/divaibhav/helloworld
1 Comment
You are ignoring any error messages emitted by your script.
Remove all use of p.getInputStream(), and replace it with a call to inheritIO():
try {
ProcessBuilder pb = new ProcessBuilder(
"/Users/Folder/AnotherFolder/Another/Final/clone.sh");
pb.inheritIO();
p = pb.start();
p.waitFor();
} catch (IOException | InterruptedException) {
e.printStackTrace();
}
When you were calling p.getInputStream(), you were only reading the standard output of the process. inheritIO() will cause both the standard output and the standard error of the child process to appear in the Java process's own standard output and standard error. This will allow you to see all diagnostic messages printed by the script. In particular, error messages usually appear on standard error, not standard output.
3 Comments
inheritIO() is a lot easier. And programs really should use ProcessBuilder instead of Runtime.exec.tar -cvf commands that would mysteriously "not work". Paying attention (explicitly) to StdError caught bugs. Yes, it's kind of a pain