Getting error in calling shell script in windows e

2019-08-29 10:46发布

问题:

I want to call shell script on windows environment using java code. I am trying to execute code below to run my test script(not actual script):

Java Code:

public static void main (String args[]) {
        Runtime r = Runtime.getRuntime();
        try {
            Process p = r.exec("C:\\cygwin\\bin\\bash -c '/cygdrive/d/scripts/test.sh'");
            InputStream in = p.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            System.out.println("OUT:");
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

            in = p.getErrorStream();
            br = new BufferedReader(new InputStreamReader(in));
            System.out.println("ERR:");
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

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

test.sh

#!/bin/bash

rm -rf ./test

But I am getting these error and script in not able to remove the directory.

ERR: /cygdrive/d/ereader/scripts/test.sh: line 2: $'\r': command not found /cygdrive/d/ereader/scripts/test.sh: line 3: rm: command not found

Another thing, when I run the script from the cygwin terminal it works fine. I checked the path variable they all are fine. But I try to execute same script through java code it gives error..

Now how to tell java program where to refer for rm commands?

回答1:

probably you will need to set the PATH variable first thing in the test.sh script. Make sure rm is in the PATH you set



回答2:

The giveaway is the '\r' error.

Windows and Unix (which includes Mac and Linux) use different representations of a new line. Windows uses '\r\n' while Unix simply uses '\n'. Most programming editors account for this and only insert a '\n' so they work with Unix tools.

I would suggest retyping your shell script in another editor like Notepad++ (which only inserts '\n'), or make sure your current editor is set to use Unix newlines. You have to retype it or the bad '\r\n' sequences will get copied over. You might have some luck in doing a replace-all but that always acts flaky for me.



回答3:

Not really answer. You could try following to narrow down the problem

  1. Use ProcessBuilder instead of Process. It is much more friendly to handle arguments.
  2. Set absolute path to rm (/bin/rm ) in the script
  3. remove using absolute path to directory or remove after verifying you are in the correct directory..

The bash prompt you have is result of cygwin.bat calling bash with --login. It will have path variables and other usesul stuff sources. bash -c does not do it.

  1. Try launching bash.exe with bash -l -c <command> : This sources the bash profile.