我试图用 ProcessBuilder
执行java的bash脚本我的代码是:
Process createUser = buildProcess(
"/bin/su",
"-c",
""/opt/somedir/testdir/current/bin/psql",
"--command",
commandForUserCreation,
/* "'select * from users'", */
"--dbname",
"mydbname"",
"myuser"
);
问题是我收到错误:
/bin/su: unrecognized option '--dbname'
如果我将 echo
放在命令的第一名中,它将在bash中打印正确的命令,如果我复制/粘贴此命令,则可以工作!
请帮助我解决此问题。
您需要提供整个命令以通过su
作为单个参数执行。尝试以下操作:
Process createUser = buildProcess(
"/bin/su",
"-c",
"/opt/vmware/vpostgres/current/bin/psql --command " + commandForUserCreation + " --dbname mydbname",
myuser
);
这是我在ProcessBuilder中使用的内容:
String[] command = new String[] {"echo", "Hello"};
String workspace = "/bin/su";
System.out.println("Trying to run command: "+ Arrays.toString(command));
ProcessBuilder probuilder = new ProcessBuilder(command);
probuilder.directory(new File(workspace));
Process process = probuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:n",Arrays.toString(command));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
我希望它有帮助。