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.
Inside the script, we can use the $ symbol followed by the integer to access the arguments passed. For example, $1 , $2 , and so on. The $0 will contain the script name.
As we've seen in this quick tutorial, we can execute a shell command in Java in two distinct ways. Generally, if you're planning to customize the execution of the spawned process, for example, to change its working directory, you should consider using a ProcessBuilder. As always, you'll find the sources on GitHub.
Syntax for defining functions: To invoke a function, simply use the function name as a command. To pass parameters to the function, add space-separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3, etc.
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
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);
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);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With