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.
If you run it using
bashit 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.