从Java/Groovy运行复合Shell命令 [英] Run a compound shell command from Java/Groovy

查看:58
本文介绍了从Java/Groovy运行复合Shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试从Groovy脚本运行复合shell命令时遇到了麻烦.这是您使用&&"分隔的命令之一因此,如果第一个命令失败,则第二个命令将永远不会运行.无论出于什么原因,我都无法正常工作.我正在使用:

I got stuck trying to run a compound shell command from a Groovy script. It was one of those commands where you separate with "&&" so that the 2nd command never runs if the 1st one fails. For whatever reason I couldn't get it to work. I was using:

println "custom-cmd -a https://someurl/path && other-cmd -f parameter".execute([], new File('/some/dir')).text

shell不断误解命令抛出的错误,例如"custom-cmd -f无效选项",就像忽略了&&"一样在两者之间.我也尝试使用分号,但并不幸运.我尝试使用直接的Java API Runtime.getRuntime().exec()并将命令拆分为一个数组.我尝试将命令包装在单引号中,并将其提供给'/bin/sh -c',但没有任何效果.

The shell kept misinterpreting the command throwing errors like "custom-cmd -f invalid option" It was like it was ignoring the "&&" in between. I tried using a semi-colon as well but was not lucky. I tried using straight Java APIs Runtime.getRuntime().exec() and splitting the command into an array. I tried wrapping the command in single quotes and giving it to '/bin/sh -c' but nothing works.

如何从Java运行复合shell命令?我知道我过去曾经做过,但是今天我不知道.

How do you run a compound shell command from Java? I know I've done this in the past but I cannot figure it out today.

推荐答案

使用Groovy,execute的列表形式应该起作用:

With groovy, the list form of execute should work:

def out = ['bash', '-c', "custom-cmd -a https://someurl/path && other-cmd -f parameter"].execute([], new File('/some/dir')).text

当然,您可能希望在进程上使用 consumeProcessOutput 方法,就像输出太大一样,调用文本可能会阻塞

Of course you may want to use the consumeProcessOutput method on process, as if the output is too large, calling text may block

这篇关于从Java/Groovy运行复合Shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆