【问题标题】:how to validate unix command with java如何使用 java 验证 unix 命令
【发布时间】:2014-10-08 03:16:09
【问题描述】:

我正在编写一个 java 程序,它接受命令并在 unix shell 中运行它。我设法得到了输出,但是我需要程序来检测给定的命令是否无效,现在,如果我输入一个无效的命令,它会给我一个错误。否则,它工作正常。有人可以帮我吗?这是我的代码:

public class TestCommand {

    public static void main(String[] args) {

        TestCommand obj = new TestCommand();
        String sentence ="";
        Scanner scn = new Scanner(System.in);

         while (sentence != " ")
        {
             if (sentence !="exit")
             {   
                 System.out.println("> ");
                 sentence = scn.nextLine();

                 String outPut = obj.executeCommand(sentence);
                 System.out.println(outPut + "\n");
             }
             else
             {
                 System.exit(2);
             }
        }




    }

    private String executeCommand(String sentence)
    {
        StringBuffer output = new StringBuffer();


        Process p;

        try
        {
            p = Runtime.getRuntime().exec(sentence);
            p.waitFor();

            BufferedReader bfrd = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = bfrd.readLine())!= null)
            {
                output.append(line);

            }
            bfrd.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return output.toString();
    }

}

【问题讨论】:

  • 不是直接点,但不要测试String==!= 是否相等。你应该使用类似!sentence.equals(" ")!sentence.equals("exit")
  • 感谢您的建议 :) 我会更改它...
  • 您正在尝试确定给您的 shell 命令是否是语法上有效的 shell 命令?所以echo foo bar 可以,但echo 'foo 不行?

标签: java shell unix


【解决方案1】:

Unix shell 语言异常复杂。在 java 中重新实现足够多的代码来测试正确性将是一项艰巨的任务。如果您只是想了解某些 shell 代码是否语法正确,可以使用 bash-n 选项:

bash -n file_with_code_to_test

或者:

bash -n -c string_with_code_to_test

这里的关键是-n 选项。它告诉bash 读取命令并检查它们的语法而不执行它们。因此,这是可以安全运行的。

您可以像运行其他 bash 命令一样从 java 运行这些命令。

bash 将返回退出代码 0 如果代码语法正确。如果不是,它将打印错误消息并返回退出代码1

为了清楚起见,这会检查语法。例如,它将测试所需文件或命令是否存在,只有当它们确实存在时才会运行代码。

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多