簡體   English   中英

在Groovy中如何進行shell擴展?

[英]How to have shell expansion in Groovy?

在bash中運行以下命令:

echo *

給出以下輸出:

echo.groovy file1 file2

通過groovy運行相同的命令:

print 'echo *'.execute().text

給出:

*

我意識到這是因為*擴展是由Shell完成的。 所以我嘗試這樣:

print '/bin/bash -c "echo *"'.execute().text

這一點都沒有。

如何在利用Shell擴展的同時在Groovy中執行Shell命令?

使用列表而不是字符串來確保參數正確傳遞且不會被誤解:

println(['/bin/bash', '-c', 'echo *'].execute().text)

擴展Raniz給出的答案,您現有的具有多行shell擴展好處的多行shell腳本可以按以下方式執行:

def command='''echo *
START=1
END=10
for ((i=START; i<=END; i++))
do
   echo "i: $i"
done
'''

print (['/bin/bash', '-c', command].execute().text)

輸出:

echo.groovy file1 file2
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
i: 10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM