Running Bash Script in Java

旧街凉风 提交于 2019-12-12 00:17:27

问题


So essentially, I am trying to run the command "/dir/command -arg" to change the LED color on a USB device in Java. I am using Ubuntu 10.04. When I run the command from the terminal, it works just fine.

However, I tried every iteration of Runtime.exec() that I could find and none of them seem to work. I then created a script with the following contents:

#!/bin/bash
echo "hello"
/dir/command -arg

when I run this from a terminal it works just fine. However when I run

@Override
public void run() {
    String[] lookupCmd = {"/bin/sh","-c", "sh /dir/script.sh"};
    try {
      Runtime runtime = Runtime.getRuntime();
      Process lookupProc = runtime.exec(lookupCmd);
      lookupProc.waitFor();
      BufferedReader reader = new BufferedReader(new InputStreamReader(lookupProc.getInputStream()));
      String line = reader.readLine();        
      while (line != null) {
        id.add(line);
        System.out.println(line);
        line = reader.readLine();
      }
    } catch (Exception e) {
      System.err.println(e);
    }
  }

"hello" print but nothing else. There is no error.

My other command should not yield any output, but simply change the color of an LED. However when I run it with the same command but a different arg which yields an ouput, it still only prints "hello".

I also made sure that my user has permissions to the /dev folder with the usb device.


回答1:


I wasn't running the error stream, so I've added that.

After that I realized I was missing an environment variable, so added:

String[] envar = {"VAR=path"}

and called:

runtime.exec(lookupCmd, envar);

Works great now.



来源:https://stackoverflow.com/questions/11955509/running-bash-script-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!