繁体   English   中英

Groovy:如何在groovy中执行复杂的shell命令?

[英]Groovy: How to execute complex shell command in groovy?

我希望能够执行嵌套的shell命令。 例如;

final String cmd = 'for i in pom.xml projects.xml; do find . -name $i | while read fname; do echo $fname; done;done'

我尝试了以下语法,但无法让它运行。

  1. def result = cmd.execute();
  2. def result = ['sh', '-c', cmd].execute();
  3. def result = ('sh -c for i in pom.xml projects.xml; do find . -name $i | while read fname; do echo $fname; done;done').execute()

我很感激这里的帮助。

这应该工作:

def cmd = [
  'bash',
  '-c',
  '''for i in pom.xml projects.xml
    |do
    |  find . -name $i | while read fname
    |  do
    |    echo $fname
    |  done
    |done'''.stripMargin() ]

println cmd.execute().text

(我已经格式化了命令文本,所以它在这里看起来更好,你可以把它保存在一行中)

我也相信你的命令可以被替换为:

find . -name pom.xml -o -name projects.xml -print

或者,在Groovy中:

def files = []
new File( '.' ).traverse() { 
  if( it.name in [ 'pom.xml', 'projects.xml' ] ) {
    files << it
  }
}

println files

谢谢你的帮助。 这是一个很棒的社区。 在传递环境和工作目录信息后,我能够正常工作。

def wdir = new File( "./", module ).getAbsoluteFile() ;
def env = System.getenv();
def envlist = [];
env.each() { k,v -> envlist.push( "$k=$v" ) }
final String cmd = 'for i in pom.xml projects.xml; do find . -name $i | while read fname; do echo $fname; done;done'
proc = ["bash", "-c", cmd].execute(envlist , wdir);

暂无
暂无

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

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