6

有没有办法使用 spring-shell 在同一行发送多个命令。例如:

shell> add 1 2; add 3 4
3
7

我注意到,如果我从 运行我的应用程序Intellij,我可以复制粘贴几个命令,它会正常工作:

add 1 2
add 3 4

但是当我在 bash 中运行可执行 jar 时它不起作用。我认为这是因为Terminal不同。在Intellij它是一个DumbTerminal,当我在 bash 中运行它时,它是一个PosixSysTerminal

4

1 回答 1

2

根据这个脚本命令接受一个本地文件作为参数,并将重放在那里找到的命令,一次一个。从文件中读取的行为与在交互式 shell 中的行为完全相同,因此以 // 开头的行将被视为注释并被忽略,而以 \ 结尾的行将触发行继续。在 spring 中不可能在一行上传递多个命令- shell ,但是您可以修改函数以接收字符串然后拆分它或接收字符串数组,然后自己处理字符串或数组。

@ShellMethod("Add or subtract ,two integers together.")
    public static String add(String args) {
     args=args.trim();
    String output="";
    if(args.contains(";")){
        for(String arg:args.split(";"))
        {
              arg=arg.trim();
   
            if(arg.split(" ").length==3)
            {
                int first_fig=0;
                int second_fig=0;
                try{
                    first_fig=Integer.parseInt(arg.split(" ")[1]);
                    second_fig=Integer.parseInt(arg.split(" ")[2]);
                }catch (Exception ex){
                  //  System.out.println("Invalid Argument");
                    output+="Invalid Argument\n";
                    continue;
               
                    

                }
                if(arg.split(" ")[0].equalsIgnoreCase("add"))
                {
                    output+= (first_fig+second_fig)+"\n";
                    continue;
                  
                    

                }else  if(arg.split(" ")[0].equalsIgnoreCase("subtract"))
                {
                    output+= (first_fig-second_fig)+"\n";
                    continue;
                }else{
                    output+="Invalid Argument\n";
                    continue;

                }

            }else{
                output+="Invalid Argument\n";
                continue;
            }

        }
    }else{
        if(args.split(" ").length==3) {
            int first_fig = 0;
            int second_fig = 0;
            try {
                first_fig = Integer.parseInt(args.split(" ")[1]);
                second_fig = Integer.parseInt(args.split(" ")[2]);
            } catch (Exception ex) {
                output+="Invalid Argument\n";
          
            }
            if (args.split(" ")[0].equalsIgnoreCase("add")) {
               
                output+= (first_fig+second_fig)+"\n";

            } else if (args.split(" ")[0].equalsIgnoreCase("subtract")) {
            
                output+= (first_fig-second_fig)+"\n";
            } else {
              //  System.out.println("Invalid Argument");
              
                output+="Invalid Argument\n";

            }
        }else{
           // System.out.println("Invalid Argument");
         
            output+="Invalid Argument\n";
        }
    }

    return output;
}

然后,您可以轻松地将其称为:

shell> add 1 2; add 3 4
于 2020-07-29T10:20:19.677 回答