0

I am trying to run a shell script from Java code.

Shell Script :

        function print() {
            echo "First Script"
        }
        print
        echo "Hello"

Java Code :

        final String cmd = "sh test.sh";
        final Process p = Runtime.getRuntime().exec(cmd);
        InputStream is = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
          System.out.println(line);
        }

        is = p.getErrorStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        while ((line = br.readLine()) != null) {
          System.out.println(line);
        }

But when I run the above code I get this error test.sh: 1: Syntax error: "(" unexpected.

Same code works fine when I tried in a command line and I am able to see the output. I also tried dos2unix and ran the java code, but still no luck. Any kind of help will be really appreciated.

Seki
  • 11,135
  • 7
  • 46
  • 70
Lolly
  • 34,250
  • 42
  • 115
  • 150

3 Answers3

3

If you run it using bash it will work.

I would (also) start the script with #!/bin/bash. That way the script itself determines which shell it will use, rather than relying on whoever invokes it. As noted below, you can still invoke the script using any scripting process, but the shebang will highlight which scripting language/dialect is in use.

Note also the issues surrounding invoking processes from Java and collecting stdout/sterr.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • The second part of the advice is bogus. If you run a script using explicit `sh script.sh`, then the shebang is ignored. The shebang is only interpreted by the kernel when executing a text file that is marked executable (`chmod +x`). – Fred Foo Oct 10 '12 at 11:58
  • I don't think it is bogus as such. My point is that providing the #! means you don't *have* to invoke using a particular shell. I appreciate that you can provide the script as an argument to any shell process. I will amend the answer to be clearer, however – Brian Agnew Oct 10 '12 at 11:59
1

Most likely, on your system /bin/sh is a POSIX-compatible shell rather than Bash (this is the case on Ubuntu and Debian, as well as most commercial Unices). In POSIX shells, don't use the function keyword:

print() {
    echo "First Script"
}
print
echo "Hello"

should work. (And that form works in Bash as well.)

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
-2

Verrify your Java version match with your OS. It is possible your OS is 32b and Java is 64 version.

chaps
  • 1
  • While your answer may solve the question, it is always better if you can provide a description of what the issue was and how your answer solves it. This is a suggestion for further improving this and future answers. – Luís Cruz Oct 10 '14 at 15:11