2012-08-07 44 views
2

外部過程中,我有我想從常規執行類似運行從常規

some_shell_script.sh param1 "report_date=`some_function 0 \"%Y%m%d\"`" 

該腳本命令行成功運行bash腳本,但是當我嘗試在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 
} 

功能定義看起來像當我運行從常規外部腳本它沒有父進程的背景下啓動不同的程序。我的意思是沒有父進程的函數定義存在。

任何人都知道如何應對這種情況?

回答

1

絕對檢查出@Reimeus指出的那些引號。我對這些有些懷疑。

此外,some_function()可以在~/.bashrc/etc/bash.bashrc或在任的,當你運行bash的交互的源文件中定義。如果您運行腳本,則不會發生這種情況。 (這有利於使腳本運行預見的 - 你不能有你的腳本依賴於人的登錄環境)

如果是這樣的話,移動some_function()到另一個文件,並把它的完整路徑,在BASH_ENV變量,以便bash在處理腳本時選擇它。

人的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] 
+0

不確定這是相關的,但**出口-f some_function **之前的常規會話解決了問題 – user1582639 2012-08-08 13:38:06

+0

這將適用於您的登錄環境。 'export -f'將函數定義強制到腳本的環境中,該腳本又將其傳遞給由ProcessBuilder創建的bash實例。 *小心*,如果你把groovy腳本給別人,他們的環境可能沒有你定義的'some_function'。 – 2012-08-08 13:46:09

1

這似乎是一個路徑問題。你能把腳本的完整路徑再試一次嗎?

+0

看起來像它在配置文件中定義的。我不知道路徑,它返回函數定義,但不是路徑 – user1582639 2012-08-07 17:48:57

2

您應該用單引號替換命令定義中的雙引號。

def command = 'some_shell_script.sh param1 "report_date=`some_function 0 "%Y%m%d_%H%M%S"`'

地址:

println command 

,以確保您正在執行正確的命令。

還打開一個新的bash shell並確保some_function已定義。

0

免責聲明:沒有與限制這種解決方案,殼子腳本命令在部署之前應適當地測試。然而,如果不需要多線程,例如,例如功能立即提供了一些簡短的結果,我有一個替代方案,我在here實施。

例如,如果mycmd結果取決於在~/.bashrc設置環境變量我能顯示其結果:(嘗試作爲一個Groovy的腳本/ 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 }