![](/img/trans.png)
[英]in groovy run process failure with command having spaces in file arg
[英]Run external process from groovy
我有一個bash腳本,我想從groovy執行
some_shell_script.sh param1 "report_date=`some_function 0 \"%Y%m%d\"`"
該腳本從命令行成功運行,但是當我嘗試從Groovy執行該腳本時
def command = "some_shell_script.sh param1 "report_date=`some_function 0 \"%Y%m%d_%H%M%S\"`""
def sout = new StringBuffer()
def serr = new StringBuffer()
//tried to use here different shells /bin/sh /bin/bash bash
ProcessBuilder pb = new ProcessBuilder(['sh', '-c',command])
Process proc = pb.start()
proc.consumeProcessOutput(sout, serr)
def status = proc.waitFor()
println 'sout: ' + sout
println 'serr: ' + serr
我有以下錯誤
serr: sh: some_function: command not found
與此同時
which some_function
返回類似的函數定義
some_function ()
{
;some definition here
}
看起來當我從groovy運行外部腳本時,它啟動了沒有父進程上下文的其他進程。 我的意思是不存在父進程的函數定義。
有人提示如何應對這種情況嗎?
您應該用單引號替換命令定義中的雙引號。
def command = 'some_shell_script.sh param1 "report_date=`some_function 0 "%Y%m%d_%H%M%S"`'
加:
println command
以確保您正在執行正確的命令。
還要打開一個新的bash shell並確保定義了some_function
。
這似乎是路徑問題。 您可以將完整路徑放在腳本中,然后重試嗎?
一定要按@Reimeus的指示檢查那些報價。 我對此有些懷疑。
另外,當您以交互方式運行bash時, some_function()
可以在~/.bashrc
, ~/.bashrc
/etc/bash.bashrc
或任何一個源文件中定義。 如果運行腳本,則不會發生這種情況。 (這有利於使腳本可預測地運行-您不能讓腳本依賴於人們的登錄環境。)
如果是這種情況,請將some_function()移至另一個文件,並將其完整路徑放入BASH_ENV變量中,以便bash在處理腳本時將其拾取。
男子猛擊:
When bash is started non-interactively, to run a shell script, for
example, it looks for the variable BASH_ENV in the environment, expands
its value if it appears there, and uses the expanded value as the name
of a file to read and execute. Bash behaves as if the following com-
mand were executed:
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
but the value of the PATH variable is not used to search for the file
name.
[Manual page bash(1) line 158]
免責聲明: 此解決方案有局限性, 並且應該在部署之前正確測試shell子腳本命令。 但是,如果不需要多線程, 例如該函數立即提供了一些簡短的結果,則可以在這里實現。
例如 ,如果mycmd
的結果取決於~/.bashrc
設置的環境變量,我可以顯示其結果:(嘗試作為groovy-script / v1.8.1,是的,這是一個愚蠢的示例,可能有風險!)
commands = '''source ~/.bashrc; cd ~/mytest; ./mycmd'''
"bash".execute().with{
out << commands
out << ';exit $?\n'
waitFor()
[ok:!exitValue(), out:in.text, err:err.text]
}.with{ println ok?out:err }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.