function 功能
什么是『函數 (function)』功能啊?簡單的說,其實, 函數可以在 shell script 當中做出一個類似自訂運行命令的東西,最大的功能是, 可以簡化我們很多的程序碼~
function 的語法是這樣的:
function fname() { 程序段 }
那個 fname 就是我們的自訂的運行命令名稱~而程序段就是我們要他運行的內容了。 要注意的是,因為 shell script 的運行方式是由上而下,由左而右, 因此在 shell script 當中的 function 的配置一定要在程序的最前面, 這樣才能夠在運行時被找到可用的程序段喔!
好~我們將 sh12.sh 改寫一下,自訂一個名為 printit 的函數來使用喔:
[root@www scripts]# vi sh12-2.sh #!/bin/bash # Program: # Use function to repeat information. # History: # 2005/08/29 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH function printit(){ echo -n "Your choice is " # 加上 -n 可以不斷行繼續在同一行顯示 } echo "This program will print your selection !" case $1 in "one") printit; echo $1 | tr 'a-z' 'A-Z' # 將參數做大小寫轉換! ;; "two") printit; echo $1 | tr 'a-z' 'A-Z' ;; "three") printit; echo $1 | tr 'a-z' 'A-Z' ;; *) echo "Usage $0 {one|two|three}" ;; esac
以上面的例子來說,鳥哥做了一個函數名稱為 printit ,所以,當我在后續的程序段里面, 只要運行 printit 的話,就表示我的 shell script 要去運行『 function printit .... 』 里面的那幾個程序段落羅!當然羅,上面這個例子舉得太簡單了,所以你不會覺得 function 有什么好厲害的, 不過,如果某些程序碼一再地在 script 當中重復時,這個 function 可就重要的多羅~ 不但可以簡化程序碼,而且可以做成類似『模塊』的玩意兒,真的很棒啦!
另外, function 也是擁有內建變量的~他的內建變量與 shell script 很類似, 函數名稱代表示 $0 ,而后續接的變量也是以 $1, $2... 來取代的~ 這里很容易搞錯喔~因為『 function fname() { 程序段 } 』內的 $0, $1... 等等與 shell script 的 $0 是不同的。以上面 sh12-2.sh 來說,假如我下達:『 sh sh12-2.sh one 』 這表示在 shell script 內的 $1 為 "one" 這個字串。但是在 printit() 內的 $1 則與這個 one 無關。 我們將上面的例子再次的改寫一下,讓你更清楚!
[root@www scripts]# vi sh12-3.sh #!/bin/bash # Program: # Use function to repeat information. # History: # 2005/08/29 VBird First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH function printit(){ echo "Your choice is $1" # 這個 $1 必須要參考底下命令的下達 } echo "This program will print your selection !" case $1 in "one") printit 1 # 請注意, printit 命令后面還有接參數! ;; "two") printit 2 ;; "three") printit 3 ;; *) echo "Usage $0 {one|two|three}" ;; esac
在上面的例子當中,如果你輸入『 sh sh12-3.sh one 』就會出現『 Your choice is 1 』的字樣~ 為什么是 1 呢?因為在程序段落當中,我們是寫了『 printit 1 』那個 1 就會成為 function 當中的 $1 喔~ 這樣是否理解呢? function 本身其實比較困難一點,如果你還想要進行其他的撰寫的話。 不過,我們僅是想要更加了解 shell script 而已,所以,這里看看即可~了解原理就好羅~ ^_^
轉自 http://vbird.dic.ksu.edu.tw/linux_basic/0340bashshell-scripts_4.php