函數能夠在shell script當中作一個相似自定義執行命令,最大的功能就是能夠簡化咱們不少的程序代碼。須要注意的是shell script的執行方式是由上而下/由左而右,所以在shellscript當中的function的設置必定要在程序的最前面,這樣纔可以在執行時被找到可用的程序段。shell
#!/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腳本:bash
#!/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