简体   繁体   中英

Groovy: How to execute complex shell command in groovy?

I would like to be able to execute a nested shell command. For example;

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

I had tried the following syntax but wasn't able to get it running.

  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()

I would appreciate the help here.

This should work:

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

(I've formatted the command text so it looks better here, you could keep it all in one line)

I also believe your command could be replaced by:

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

Or, in Groovy:

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

println files

Thanks for all the help. This is a great community. I was able to get this working after passing in the environment and working directory information.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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