繁体   English   中英

在Groovy中使用grep进行if if else语句高级

[英]Advanced if else statements with grep in Groovy

我有下面的Jenkinsfile它将grep从URL的字符串,它将根据输出将通知发送到Slack。

stage('Check if present') {
    steps  {
        script{   
         sh """
          if curl -s http://example.foo.com:9000 | grep -q "ERROR"
            then  
              slackSend channel: '#team', message: "Pipeline has been failed due to due to an error, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'    
                echo "Scan result: ERROR" && exit 1  
            elif curl -s http://example.foo.com:9000 | grep -q "WARN"
            then
           slackSend channel: '#team', message: "Pipeline is in WARN state due to a warning, please investigate:${env.BUILD_URL} : http://example.foo.com:9000", teamDomain: 'example', tokenCredentialId: 'foo'
             fi"""
         }
       }
    }

绝对slackSend通知将不起作用,因为它是一个插件。 我正在寻找在Groovy中执行相同操作的方法,以便可以实现slackNotification。

作为示例,我在Groovy中尝试了以下逻辑。 但这没有用,因为即使该行不存在也就是找到了打印行。

stage('test logic'){
steps{
 script{
     if ('curl -s http://example.foo.com:9000'.execute() | 'grep foo'.execute())
        println("The line is found")
     else {
         println("The line is not found")
         exit 1
     }
       }

}}

您可以只使用Groovy(更准确地说是Java)的.contains(String)方法来检查某个字符串是否包含其他字符串。 同样,当您在管道中执行命令时,您可以捕获该命令的标准输出。

码:

stage('test logic'){
  steps{
   script{
     def commandStdout = sh(returnStdout: true, script: "curl -s http://example.foo.com:9000"
     if (commandStdout.contains("foo")) {
        println("The line is found")
     }else {
         println("The line is not found")
         exit 1
     }
   }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM