簡體   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