這篇文章主要介紹了Shell腳本中使用function(函數)示例,本文着重講解的是如何在shell腳本中使用自定義函數,並給出了兩個例子,需要的朋友可以參考下
函數可以在shell script當中做一個類似自定義執行命令,最大的功能就是可以簡化我們很多的程序代碼。需要注意的是shell script的執行方式是由上而下/由左而右,因此在shellscript當中的function的設置一定要在程序的最前面,這樣才能夠在執行時被找到可用的程序段。
#!/bin/bash # Program # This program is to show the use of "function" # History # 2013/5/4 by Lvcy First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/loacl/sbin:~/bin export PATH #輸出統一信息 function printInfo () { echo -n "Your choice is " } #將小寫字符轉換為大寫字符 function dotr() { tr 'a-z' 'A-Z' } read -p "Please input your choice(one|two|three|four):" num #用case做條件判斷 case $num in "one") printInfo; echo $num | dotr ;; "two") printInfo; echo $num | dotr ;; "Three") printInfo; echo $num | dotr ;; "four") printInfo; echo $num | dotr ;; esac exit 0
下面是一個一般的帶有function函數的shell腳本:
#!/bin/bash # Program # This program is show the params of function # History # 2013/5/14 by Lvcy First release PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin export PATH function printInfo() { echo "Your choice is $1" } case $1 in "one") printInfo 1 ;; "two") printInfo 2 ;; "three") printInfo 3 ;; "four") printInfo 4 ;; esac exit 0
若以上文件名為sh02.sh,則執行這個script的命令為:
sh sh02.sh one