【发布时间】:2021-09-28 20:36:12
【问题描述】:
在 gradle 7 中我创建了这个方法:
def shellCmd(String cmd) {
exec {
executable "sh"
args "-c", cmd
}
}
还有这个“纯”的 groovy 版本:
def shellCmd2(String cmd) {
def process = cmd.execute()
def output = new StringWriter(), error = new StringWriter()
process.waitForProcessOutput(output, error)
}
我从另一种方法调用,例如:
def myMethod() {
shellCmd('ls -la')
}
我现在正在尝试让它与多行(jenkins 之类)shell 命令一起工作:
def myMethod() {
def cmd = """
for i in \$(ls -la); do
if [[ \$i == 'settings.gradle' ]]; then
echo "Found $i"
fi
done
"""
shellCmd(cmd)
}
但它失败了:
script '/home/user/samples/build.gradle': 47: Unexpected input: 'i' @ line 47, column 5.
for i in $(ls -la); do
^
1 error
可能我在这里违反了所有规则,但有任何输入吗?
也尝试了这里的大部分建议:
What's wrong with Groovy multi-line String?
但到目前为止还没有运气。
另外基于下面的建议,我尝试使用shellCmd2 方法(我倾向于使用普通的常规方法,以便更容易在 gradle 之外进行调试):
def myMethod() {
def cmd = """
for i in \$(ls -la); do
if [ \$i = 'settings.gradle' ]; then
echo "Found \$i"
fi
done
"""
shellCmd2(cmd)
}
但这给出了:
Caught: java.io.IOException: Cannot run program "for": error=2, No such file or directory
java.io.IOException: Cannot run program "for": error=2, No such file or directory
看来for 关键字现在引起了问题。
【问题讨论】:
-
不确定是否可以将多行字符串作为命令行。我相信詹金斯正在创建一个 temp.sh 文件并执行它。