【问题标题】:groovy execute with parameters containing spacesgroovy 使用包含空格的参数执行
【发布时间】:2009-04-24 14:49:38
【问题描述】:

如何为groovy中字符串的execute方法提供包含空格的参数?像在 shell 中那样添加空格并没有帮助:

println 'ls "/tmp/folder with spaces"'.execute().text

这会给 ls 调用提供三个损坏的参数。

【问题讨论】:

    标签: groovy


    【解决方案1】:

    诀窍是使用列表:

    println(['ls', '/tmp/folder with spaces'].execute().text)
    

    【讨论】:

    • 如果命令是动态生成的或向用户询问此解决方案不起作用。保持引号的数量肯定不会那么难解析......
    【解决方案2】:

    对不起,上面的技巧都不适合我。 这段可怕的代码是唯一通过的:

        def command = 'bash ~my_app/bin/job-runner.sh -n " MyJob today_date=20130202 " ' 
        File file = new File("hello.sh")
        file.delete()       
        file << ("#!/bin/bash\n")
        file << (command)
        def proc = "bash hello.sh".execute()                 // Call *execute* on the file
    

    【讨论】:

      【解决方案3】:

      对于需要常规报价处理、管道等的人来说,一个奇怪的技巧:使用bash -c

      ['bash','-c',
      '''
      docker container ls --format="{{.ID}}" | xargs -n1 docker container inspect --format='{{.ID}} {{.State.StartedAt}}' | sort -k2,1
      '''].execute().text
      

      【讨论】:

      • 简单地说:["bash","-c","your command with spaces and quotes"].execute().text
      【解决方案4】:

      我觉得使用列表有点笨拙。

      这样就可以了:

      def exec(act) { 
       def cmd = []
       act.split('"').each { 
         if (it.trim() != "") { cmd += it.trim(); }
       }
       return cmd.execute().text
      }
      
      println exec('ls "/tmp/folder with spaces"')
      

      更复杂的例子:

      println runme('mysql "-uroot" "--execute=CREATE DATABASE TESTDB; USE TESTDB; \\. test.sql"');
      

      唯一的缺点是需要在所有参数周围加上引号,我可以忍受!

      【讨论】:

        【解决方案5】:

        你试过转义空格吗?

        println 'ls /tmp/folder\ with\ spaces'.execute().text
        

        【讨论】:

          猜你喜欢
          • 2021-05-28
          • 2018-05-30
          • 1970-01-01
          • 2014-03-06
          • 1970-01-01
          • 1970-01-01
          • 2015-06-21
          • 2018-12-08
          • 2017-06-14
          相关资源
          最近更新 更多