Shell腳本中使用function(函數(shù))示例
函數(shù)可以在shell script當中做一個類似自定義執(zhí)行命令,最大的功能就是可以簡化我們很多的程序代碼。需要注意的是shell script的執(zhí)行方式是由上而下/由左而右,因此在shellscript當中的function的設(shè)置一定要在程序的最前面,這樣才能夠在執(zhí)行時被找到可用的程序段。
#!/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
#輸出統(tǒng)一信息
function printInfo ()
{
echo -n "Your choice is "
}
#將小寫字符轉(zhuǎn)換為大寫字符
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函數(shù)的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,則執(zhí)行這個script的命令為:
sh sh02.sh one
相關(guān)文章
Shell腳本實現(xiàn)根據(jù)端口號kill相應(yīng)進程功能
這篇文章主要介紹了Shell腳本實現(xiàn)根據(jù)端口號kill相應(yīng)進程功能,本文相對簡單,只有一句話,需要的朋友可以參考下2014-12-12Linux shell條件判斷if中的-a到-z的意思【推薦】
這篇文章主要介紹了Linux shell條件判斷if中的-a到-z的意思,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08