【问题标题】:Running Bash script using Java使用 Java 运行 Bash 脚本
【发布时间】:2020-02-11 01:08:24
【问题描述】:

我正在尝试运行 Bash 脚本来比较两个文件以查看它们是否相同(最后几行除外)。我编写的脚本在我手动运行时运行良好,但是,因为我希望脚本在 java 程序之后立即运行,所以我已经做到了,所以 java 程序在完成其他所有操作后运行脚本,但是当这种情况发生时我收到语法错误。

有人可以解释为什么当我从 java 程序运行 bash 脚本时会发生这种情况,以及我该如何解决它。

fileChangeCheck.sh

#!/bin/bash

if [[ -f output/newfile.json ]]
then

echo "File found"
errorTest=$(tail -n 1 output/newfile.json)

if [[ $errortest=} ]]
then

diff <(head -n -3 output/current.json) <(head -n -3 output/newfile.json) > output/check.txt

if [[ -s output/check.txt ]]
then
  echo "$(date "+%d-%m-%Y %H:%M:%S") - Check had Data" >> logs/log.txt
  mv output/current.json output/archive/current.$(date "+%Y%m%d%H%M%S").json
  mv output/newfile.json output/current.json
  rm output/check.txt
else
  echo "$(date "+%d-%m-%Y %H:%M:%S") - Check was empty" >> logs/log.txt
  rm output/newfile.json
  rm output/check.txt
fi
fi
fi

Java 代码

    public static void filecheck() throws Exception {
        Process p = Runtime.getRuntime().exec("sh "+directory+"fileChangeCheck.sh");
        p.waitFor();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));


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

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

错误信息

$ java -jar retrieve.jar
fileChangeCheck.sh: line 12: syntax error near unexpected token `('
fileChangeCheck.sh: line 12: `diff <(head -n -3 output/current.json) <(head -n -3 output/newfile.json) > output/check.txt'

非常感谢

【问题讨论】:

    标签: java bash shell unix


    【解决方案1】:

    你正在调用 sh,它只会运行这个脚本;告诉系统使用 bash 运行它的顶部“注释”被 sh 忽略,并且 sh 可能不是 bash,因此需要研究一下。这也是相当可疑的,并且很可能在许多系统上失败;我建议至少显式调用“/bin/bash”。

    这可能会解决它。如果不是,可能是当前工作目录不同的问题。

    编辑:应用评论者戴夫汤普森的建议。

    【讨论】:

    • 不被注意 -- 或者更简单地说,被忽略
    • 谢谢,这使我查看了我正在调用的内容,结果发现我的语法对于 sh 不正确,但对于 bash 很好。可能有一种更简单的方法,但为了避免使用 diff 命令的语法,我将代码更改为创建 2 个新文件并进行比较。谢谢你的建议,没有它我会迷路一段时间。
    【解决方案2】:

    Processbuilder 有许多选项可供您设置:

    try {
            final Process pr = new ProcessBuilder("fileChangeCheck.sh").directory(new File(yourDirectory)).redirectOutput(new File(logfile))
                            .start();
            pr.waitFor();
        } catch (IOException | InterruptedException e) {
            System.out.println(e.getMessage());
        }
    

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 2013-11-01
      • 2018-12-13
      • 2016-04-28
      • 2018-03-14
      • 2012-11-22
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多