无法将参数发送到来自java的bash脚本

无法将参数发送到来自java的bash脚本

问题描述:

我想通过Java在我的Ubuntu机器上运行bash脚本。 bash脚本需要2个输入作为参数,我作为一个数组传递 但是,它似乎没有将数组[0]和数组[1]的值传递给bash脚本?无法将参数发送到来自java的bash脚本

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import org.omg.CORBA.portable.InputStream; 

public class readBashScript { 

    public static void readBashScript() { 
     try { 

      String[] array = {"ys1","R"}; 

      Process proc = Runtime.getRuntime().exec("var/www/red/marsh_webreset.sh /",array); 
      BufferedReader read = new BufferedReader(new InputStreamReader(
        proc.getInputStream())); 
      try { 
       proc.waitFor(); 
      } catch (InterruptedException e) { 
       System.out.println(e.getMessage()); 
      } 
      while (read.ready()) { 
       System.out.println(read.readLine()); 
      } 
     } catch (IOException e) { 
      System.out.println(e.getMessage()); 
     } 
    } 
} 
+0

我使用Runtime.exec来解决类似的问题。我认为我的解决方案是直接在程序中包含参数来执行String – ControlAltDel 2014-09-29 18:58:29

+0

推荐的方法是使用['ProcessBuilder'](http://docs.oracle.com/javase/7/docs/api/java/lang/ ProcessBuilder.html),尽管使用shellshock这似乎是一个非常冒险的代码。 – 2014-09-29 18:59:39

+0

当你直接在程序中说你的意思是在bash脚本中吗?因为我会从用户的实时参数 – user3846091 2014-09-29 19:00:06

你传入的参数错误地尝试下面的代码:

Process proc = Runtime.getRuntime().exec("/var/www/redbutton/marsh_webreset.sh "+array[0]+" "+ array[1]+" /"); 

看看一些文档。

要传递到exec方法的第二个参数是:

envp - 字符串数组,其中的每个元素具有在格式名=值环境变量的设置,或者为null如果子进程应该继承当前进程的环境。

我推荐看看thisthis

如果要传递环境变量,可以将它们添加为数组,但必须采用格式“key = value”。

IE:

$ ONE = 1两= 2 shell.sh

然后,您可以在你的shell脚本呼应这些变量。

$回声$ ONE

+0

这是一个有效的批判,但它并没有解决问题,或者? – ControlAltDel 2014-09-29 19:03:59

+0

编辑添加实际用法。 – proulxs 2014-09-29 19:13:01

它看起来像您所呼叫的错误Runtime.exec()方法。你正在传递一个命令和一个环境变量数组,但是你想把参数传递给你正在执行的进程。您要拨打exec(String[])而不是exec(String, String[])

您可能也想看看错误流 - 它可能有一个信息错误消息。另外,我不确定命令字符串末尾的/是否有用,甚至是有效的。您可能也不想导入org.omg.CORBA.portable.InputStream

你应该在一个时间发送阵列的每个值。由于无法自行提取值,因此无法将该数组作为参数发送给bash脚本。 Process proc = Runtime.getRuntime()。exec(“/ var/www/redbutton/marsh_webreset.sh”+ array [0] +“”+ array [1] +“/”);