在 Java 中运行 Bash 脚本 [英] Running Bash Script in Java

查看:30
本文介绍了在 Java 中运行 Bash 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以本质上,我试图运行命令/dir/command -arg"来更改 Java 中 USB 设备上的 LED 颜色.我正在使用 Ubuntu 10.04.当我从终端运行命令时,它工作得很好.

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.

然而,我尝试了我能找到的 Runtime.exec() 的每一次迭代,但它们似乎都不起作用.然后我创建了一个包含以下内容的脚本:

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.

我的另一个命令不应该产生任何输出,而只是改变 LED 的颜色.但是,当我使用相同的命令但产生输出的不同 arg 运行它时,它仍然只打印hello".

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".

我还确保我的用户拥有使用 USB 设备访问/dev 文件夹的权限.

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

推荐答案

我没有运行错误流,所以我添加了它.

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"}

并调用:

runtime.exec(lookupCmd, envar);

现在效果很好.

这篇关于在 Java 中运行 Bash 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆