Keir Nellyer
Keir Nellyer

Reputation: 923

Execute sh file from Java

I am trying to execute an sh file via the following code (CentOS machine btw)

Runtime.getRuntime().exec("sh " + file.getPath());

I use this code for windows and it works fine

Runtime.getRuntime().exec("cmd /c start " + file.getPath());

Could it be because I'm using Screen in the .sh file? I am also using the java command to start the server so maybe I need to include these?

Here are the contents of the sh file

#!/bin/sh
BINDIR=$(dirname "$(readlink -fn "$0")")
cd "$BINDIR"
screen -S PrivateServer java -Xms2048M -Xmx2048M -jar somejar.jar -o true

I am also running this code from a shutdown hook, could this be the issue? This is intended because the software is a game server and it is intended so that the user can use a restart command or have it auto restart without needing to setup anything them self.

Edit: I decided to output the errors to a text file and found this "Must be connected to a terminal." any ideas? I believe this is an issue to do with using screen.

Upvotes: 0

Views: 12162

Answers (4)

iTech
iTech

Reputation: 18430

Since you confirmed that the file has executable permission, try to pass the argument as follows:

Runtime.getRuntime().exec(new String[]{"/bin/sh" ,"-c", file.getPath()});

So mainly provide the complete path for sh and use -c

Upvotes: 1

srnvs
srnvs

Reputation: 1067

It does not seem to have executable permissions, try executing "chmod +x shell_script_filename" before executing the shell script

Upvotes: 0

zeddarn
zeddarn

Reputation: 310

I recommend using org.apache.commons.exec.* to run such.

Upvotes: 0

Marcelo Tataje
Marcelo Tataje

Reputation: 3871

Yo need to set the permissions for the operation, usually the "sh" files require execution permission in order to run this scripts from a Java Application. You must run the Java application as root (sudo su) or sudo java -jar. Or set full access to your script "sudo chmod 777 ..." well, not full access, but at least chmod +x for any user that wants to execute your script.

Best regards.

Upvotes: 0

Related Questions