我正在尝试执行一个从java传递4个参数的bash脚本。我可以使用以下代码完美地执行没有参数的脚本:
try
{
String command = "bash bash/testbash.sh";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
e.printStackTrace();
}
}
try
{
String command = "bash bash/testbash.sh";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
e.printStackTrace();
}
}
所以我打算让String []将命令和参数传递给Runtime.exec(),如下所示:
try
{
String[] command ={"bash bash/testbash.sh"};
Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
e.printStackTrace();
}
}
这给了我这个错误:
try
{
String[] command ={"bash bash/testbash.sh"};
Runtime run = Runtime.getRuntime();
Process pr = run.exec(command);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null)
{
System.out.println(line);
}
}
catch (Exception e)
{
System.out.println("Exception " + e);
e.printStackTrace();
}
}
这对我没有意义。 bash文件显然存在,因为我只是将它与String命令一起使用,但是当我在String []命令中使用相同的东西时它不存在?我如何通过参数传递命令?
答案 0 :(得分:1)
String [] command = {“bash bash / testbash.sh”};
String[] command ={"bash", "bash/testbash.sh"};