问题
I have been googling for some time, and everyone seems to have a different solution, none of which appear to be working for me.
I have tried both ProcessBuilder and Runtime. Both calling the .sh file directly and feeding it to /bin/bash. With no luck.
Back to basics, my current code is as follows;
String cmd[] = { "~/path/to/shellscript.sh", "foo", "bar" };
Process p = Runtime.getRuntime().exec(cmd);
Which is giving a No such file or directory error, despite that manually running;
~/path/to/shellscript.sh foo bar
Works perfectly from bash.
I need to keep the ~ because this shellscript exists in slightly different forms for three different users.
回答1:
One option is to handle ~ yourself:
String homeDir = System.getenv("HOME");
String[] cmd = { homeDir + "/path/to/shellscript.sh", "foo", "bar" };
Process p = Runtime.getRuntime().exec(cmd);
Another is to let Bash handle it for you:
String[] cmd = { "bash", "-c", "~/path/to/shellscript.sh foo bar" };
Process p = Runtime.getRuntime().exec(cmd);
回答2:
As already mentioned, tilde is a shell-specific expansion which should be handled manually by replacing it with the home directory of the current user (e.g with $HOME if defined).
Besides the solutions already given, you might also consider using commons-io and commons-exec from the Apache Commons project:
...
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.Executor;
import org.apache.commons.io.FileUtils;
...
CommandLine cmd = new CommandLine("path/to/shellscript.sh");
cmd.addArgument("foo");
cmd.addArgument("bar");
Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(FileUtils.getUserDirectory());
exec.execute(cmd);
...
回答3:
In general, I would recommend that you use the ScriptEngine instead of System.getRuntime().exec
I think it will make things more easy for you.
Bare in mind you need for this JDK 6 and above.
In addition, regarding your specific problem - I really think that this issue should be configurable.
You can do the following:
A. Have in your .bash_rc or .bash_profile (for each user) define a path to the configuration
script using:
EXPORT MY_SCRIPT=
B. Read this value from java code, using String sciprtPath = System.getenv("MY_SCRIPT") to get the value.
C. Run the script , the way you did in your code, with scriptPath variable, or using the scriptEngine.
来源:https://stackoverflow.com/questions/13183152/executing-shell-script-with-parameters-from-java