2016-09-22 34 views
1

我已經做了足夠的搜索來發現這一點,但沒有運氣。我正在嘗試編寫一個Bash腳本,該腳本必須調用其他地方定義的函數。在Bash腳本中調用一個函數

例如,我有一個殼test.sh

#!/bin/bash 

# Shell - test.sh 

function1() { 
    echo "Inside function 1" 
} 

function1 
function2 

exit 0 

我有具有函數2不同的文件,

$ cat function2 

function2() { 
    echo "Inside function 2" 
} 

現在,當我運行test.sh, (Q1)它如何知道在哪裏可以找到function2? (Q2)沒有顯示功能2的回波輸出

任何輸入都很棒。

嗨,感謝您的回答。但是,令我驚訝的是,當我使用「$。/ test.sh」執行shell時,我得到「Inside function 1」的輸出。如果shell沒有找到「function2」,它應該拋出一個錯誤,「找不到函數或者其他東西」。我覺得不知何故該函數被調用,但消息沒有顯示。

感謝, 拉維

+0

你'source'第一(你可以用'.'作爲'source'快捷方式) –

+0

第二個文件@ DavidC.Rankin它周圍的其他方式,'source'命令是長'''命令的版本,但'.'首先出現。 – hek2mgl

+0

我總是把它倒退,謝謝。我得到的雞或雞蛋也錯'')' –

回答

-1

你必須導入具有功能2完整路徑的其他文件,有功能1.這樣,你將有機會獲得文件的功能在文件中2

+0

嗨,謝謝你的回答。但是,令我驚訝的是,當我使用「$。/ test.sh」執行shell時,我得到「Inside function 1」的輸出。如果shell沒有找到「function2」,它應該拋出一個錯誤,「找不到函數或者其他東西」。我覺得不知何故該函數被調用,但消息沒有顯示。 –

0

繼續評論,你sourcefile2file1,例如

#!/bin/bash 

# Shell - test.sh 

function1() { 
    echo "Inside function 1" 
} 

if [ -r "file2" ] ## make sure file2 is readable by file1 
then 
    . "file2"  ## source file2 in file1. 
        ## Yes the . is a command! Check 'help .' 
else    ## otherwise show error and exit 
    printf "error: file2 not readable by file1.\n" >&2 
    exit 1 
fi 

function1 
function2 

exit 0 
+0

不確定是誰投了票。答案是正確的。 – hek2mgl

+1

這是新秋季學期附帶的少年downvote小隊的新成員。 –

相關問題