【问题标题】:Executing shell script which contains a while loop from Java执行包含来自 Java 的 while 循环的 shell 脚本
【发布时间】:2014-05-13 16:20:26
【问题描述】:

我在执行包含 while 循环的 shell 脚本时遇到了严重问题。这是我的 shell 脚本:

echo Here 1
sleep 0.05
echo Here 2
sleep 0.05
echo Here 3

ic=70
while [ $ic -ge 40 ]
do
        #sleep 0.05
        ic=$[$ic-1]
        echo Here $ic
done

当我以/home/pi/tbe/testSleep.sh 的身份从终端正常执行脚本时,它正在工作。并打印所有echos。

现在我已经写了这个java方法来执行文件:

public static void main(String[] args) throws IOException, InterruptedException {       
    String command = "/home/pi/tbe/testSleep.sh";
    System.out.println("Executing command: " + command);

    Process process = new ProcessBuilder(command).start();

    BufferedReader reader = new BufferedReader(new InputStreamReader(
            process.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

    process.waitFor();
    int exitValue = process.exitValue();
    System.out.println("Command executed. Exit value: " + exitValue);
    process.destroy();  
}

当我执行它时,我只能看到以下输出:

Executing command: /home/pi/tbe/testSleep.sh
Here 1
Here 2
Here 3
Here $[70-1]
Command executed. Exit value: 0

这真的很奇怪。任何指针都会对我很有帮助。

【问题讨论】:

  • 指定要用于 shell 脚本的 shell。 String[] command = {"/bin/bash", "/home/pi/tbe/testSleep.sh"};或者在脚本本身中添加 shebang - #!/bin/bash (作为第一行)。
  • 您正在使用bash 测试您的脚本。当从 java 进程调用时,使用sh 调用脚本。该脚本利用了sh 中不支持的功能,因此行为有所不同。
  • 脚本似乎没有被正确解释,因为它不是由 shell 运行的。您是否尝试添加 #!/bin/bash?
  • 谢谢大家。问题是shebang。我没有按照@amit_g 的建议通过创建流程构建器来添加#!/bin/bash。如果您可以发表评论作为答案,我会接受。再次感谢。

标签: java shell process


【解决方案1】:

执行命令的 shell 似乎与您在命令行上运行脚本的 shell 不同。将 shell 指定为 bash。

在脚本中添加 shebang(作为第一行)。在脚本中具体说明 shell 始终是一个好习惯

#!/bin/bash

您还可以指定要用于 shell 脚本的 shell

String[] command = {"/bin/bash", "/home/pi/tbe/testSleep.sh"};

【讨论】:

    【解决方案2】:

    我在 Ubuntu 中运行了你的脚本:

    $ sh script.sh
    Here 1
    Here 2
    Here 3
    Here $[70-1]
    script.sh: 8: [: Illegal number: $[70-1]
    

    显然 $[70-1] 没有被评估,而只是被视为文字......

    我保存后看到了 cmets。他们是正确的。使用 bash(我很懒惰)给出了正确的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2019-07-20
      • 2017-09-20
      • 2019-12-10
      相关资源
      最近更新 更多