以下說明,在shell 中,使用function 的一些注意事項。
參考下列 shell 範例。
![](https://i0.wp.com/mintrabbitplus.com/wp-content/uploads/2023/09/shell_0.webp?resize=691%2C347&ssl=1)
執行以上shell,可以在tmp 中印出test_file 的內容。
![](https://i0.wp.com/mintrabbitplus.com/wp-content/uploads/2023/09/shell_1.webp?resize=517%2C128&ssl=1)
因此,可以知道執行shell script 時,會由上而下執行,所以會先執行到第一個func1,這時再往上尋找到func1 function(第一個func1),再執行function 內容,完成之後,再繼續往下執行。這時會再執行到第二個func1,這時再往上尋找到func1 function(第二個func1),再執行function 內容,最後完成script 的執行。其流程,如下圖所示。
![](https://i0.wp.com/mintrabbitplus.com/wp-content/uploads/2023/09/shell_2.webp?resize=691%2C347&ssl=1)
接著再看下面例子。我們在console 執行以下指令。
. ./test_func.sh;func1;
結果如下。
![](https://i0.wp.com/mintrabbitplus.com/wp-content/uploads/2023/09/shell_3.webp?resize=551%2C137&ssl=1)
可以知道,會先將shell 執行完成。在呼叫function 時,會由shell 的結尾,往上找尋第一個定義的function,當找到function 時,執行其內容。
![](https://i0.wp.com/mintrabbitplus.com/wp-content/uploads/2023/09/shell_4.webp?resize=691%2C347&ssl=1)
因此可以歸納出兩個結果:
- 執行shell script 時,會由上而下的執行。遇到要執行function 時,會往上找尋function,當找到function 時,會執行其內容,完成之後,再繼續往下執行。
- 在console 呼叫shell 的function 時,會由shell 的結尾,往上找尋第一個定義的function,當找到function 時,執行其內容。