【问题标题】:Possible to run multiline shell command/string in groovy/gradle?可以在 groovy/gradle 中运行多行 shell 命令/字符串吗?
【发布时间】:2021-09-28 20:36:12
【问题描述】:

在 gradle 7 中我创建了这个方法:

def shellCmd(String cmd) {
  exec {
    executable "sh"
    args "-c", cmd
  }
}

还有这个“纯”的 groovy 版本:

def shellCmd2(String cmd) {
  def process = cmd.execute()
  def output = new StringWriter(), error = new StringWriter()
  process.waitForProcessOutput(output, error)
}

我从另一种方法调用,例如:

def myMethod() {
  shellCmd('ls -la')
}

我现在正在尝试让它与多行(jenkins 之类)shell 命令一起工作:

def myMethod() {
  
  def cmd = """
   for i in \$(ls -la); do
     if [[ \$i == 'settings.gradle' ]]; then
       echo "Found $i"
     fi
   done
  """

  shellCmd(cmd)

}

但它失败了:

  script '/home/user/samples/build.gradle': 47: Unexpected input: 'i' @ line 47, column 5.
     for i in $(ls -la); do
         ^
  
  1 error

可能我在这里违反了所有规则,但有任何输入吗?

也尝试了这里的大部分建议:

What's wrong with Groovy multi-line String?

但到目前为止还没有运气。

另外基于下面的建议,我尝试使用shellCmd2 方法(我倾向于使用普通的常规方法,以便更容易在 gradle 之外进行调试):

def myMethod() {

  def cmd = """
  for i in \$(ls -la); do
    if [ \$i = 'settings.gradle' ]; then
      echo "Found \$i"
    fi
  done
  """
  
  shellCmd2(cmd)
}

但这给出了:

Caught: java.io.IOException: Cannot run program "for": error=2, No such file or directory
java.io.IOException: Cannot run program "for": error=2, No such file or directory

看来for 关键字现在引起了问题。

【问题讨论】:

  • 不确定是否可以将多行字符串作为命令行。我相信詹金斯正在创建一个 temp.sh 文件并执行它。

标签: jenkins gradle groovy


【解决方案1】:

您的多行字符串没有问题。我必须更改三件事才能使您的代码正常工作:

  1. 使用single brackets[]
  2. 使用single equal sign (=)
  3. 转义缺少的 $i 变量,该变量被解释为 Groovy 变量。

您正在使用 sh,因此您应该只使用POSIX 兼容的功能。

代码:

def shellCmd(String cmd) {
  exec {
    executable "sh" // or use another shell like bash or zsh (less portable)
    args "-c", cmd
  }
}

def myMethod() {
    def cmd = """
        for i in \$(ls -la); do
            if [ \$i = 'settings.gradle' ]; then
            echo "Found \$i"
            fi
        done
    """
    shellCmd(cmd)
}

您可以将双括号与 zsh 和 bash 等 shell 进行比较。

【讨论】:

  • 这给出了:Cannot run program "for": error=2, No such file or directory 查看我更新的示例。我认为这是因为我现在从 sh 切换到例如我正在使用的 bash?
猜你喜欢
  • 2013-05-31
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 2021-09-10
相关资源
最近更新 更多