Prosp
Prosp

Reputation: 151

Cannot run shell script from java Command Line

I'm trying to run this script shell from java, but it's not working.

I get this error message:

Process exited with an error: 1 (Exit value: 1)

Can someone help?

String pwd = "blabla";

String s_key = "0000";

String path = "C:/Files/scripts"; 

CommandLine commandLine = CommandLine.parse("C:\\Program Files (x86)\\Git\\bin\\git.exe");

commandLine.addArgument("fileName.sh");

commandLine.addArgument(password);

commandLine.addArgument(s_key);

DefaultExecutor defaultExecutor = new DefaultExecutor();

ByteArrayOutputStream sdtout = new ByteArrayOutputStream();

ByteArrayOutputStream sdterr = new ByteArrayOutputStream();

PumpStreamHandler streamHandler = new PumpStreamHandler(sdtout, sdterr);

defaultExecutor.setStreamHandler(streamHandler);

defaultExecutor.execute(commandLine);

Here is the script

#!/bin/sh

pwd=$1
s_key=$2
....
echo $pwd

it works well with git bash

  $ ./fileName.sh blabla 0000
  nkfjWmiG7dDnYUmjr6VD0A==

Upvotes: 0

Views: 1255

Answers (2)

John Weldon
John Weldon

Reputation: 40739

There are a couple issues with your code:

  • You don't seem to be inspecting the stderr/stdout of the program, or inspecting the Exception that gets thrown.
  • Git.exe doesn't take shell scripts as the first argument. As @reos says, you probably need to invoke git-bash.exe rather than git.exe

Upvotes: 0

reos
reos

Reputation: 8324

There are some points to be aware of.

  1. If you want to run the git bash command you need to execute the git-bash.exe, on the cmd console you need to execute this command:
%windir%\system32\cmd.exe /c ""C:\Program Files\Git\git-bash.exe" --login -i -- D:\temp\test.sh param1"
  1. If you want to execute it from a java app it's the same, the command you need to execute is git-bash.exe not git.exe. This is an example of running a command from java. I'm not using the objects that you're using but the simple java objects. However you can adapt it to your code.
 public static void main(String[] args) throws IOException {
          String[] command = {"C:\\\\Program Files\\\\Git\\\\git-bash.exe",
                  "D:\\temp\\test.sh",
                  "param1"};
          ProcessBuilder processBuilder = new ProcessBuilder(command);
          processBuilder.redirectErrorStream(true);
          processBuilder.start();
      }

Upvotes: 1

Related Questions