groovy中的grep命令用法

时间:2019-05-07 04:03:25

标签: bash shell jenkins groovy

如何用Groovy编写下面的shell

process_name = spin_user

if grep -i ${process_name} /tmp/output.log ; then 
  echo "Success" 
  grep -i ${process_name} output.log > final_output.log 
else 
  echo "failure" 
fi 

1 个答案:

答案 0 :(得分:0)

<<为回应评论而编辑>>

1。纯Groovy解决方案

如果您只是想在Groovy中实现bash脚本中的功能,则可以执行以下操作:

def processName = 'spin_user'
def outLog      = new File('/tmp/output.log')
def finalLog    = new File('final_output.log')

def lines       = outLog.readLines()
def hasProcess  = { it.toLowerCase().contains(processName) }

if(lines.any(hasProcess)) { 
  println "Sucess"
  finalLog.text = lines.findAll(hasProcess).join('\n')
} else { 
  println "failure"
}

应注意,如果您的日志文件很大,则有更好的搜索字符串的方法,这些方法不需要您将整个文件加载到内存中。

2。流程管理解决方案

如果您特别想从groovy中使用linux系统grep命令,那么以上内容自然对您没有帮助。下面的常规代码:

import java.util.concurrent.*

def processName = 'spin_user'
def outLog      = '/tmp/output.log'
def finalLog    = 'final_output.log'

def result = exec('grep', '-i', processName, outLog)
if (result) {
  println "success"
  new File(finalLog).text = result
} else { 
  println "failure"
}

String exec(String... args) {
  def out = new StringBuffer()
  def err = new StringBuffer()

  def process = args.toList().execute()

  process.consumeProcessOutput(out, err)
  process.waitForOrKill(5000)

  if (err) {
    println "ERROR:  executing ${args} returned ${process.exitValue()}"
    println "STDERR: ${err}"
  }

  out
}

将执行grep命令,并使您更接近所需的内容。

应注意,据我所知,shell命令中的输出重定向>在java / groovy的外部进程上很难做到,因此我们将输出写入{{1} },而不是使用输出重定向执行命令。

我还在final_output.log流程执行中添加了最大五秒钟的超时时间。这不是必需的,并且可以安全地删除该行,它只是在grep无限期阻塞的情况下提供的一种保护措施。