今天做一個試題就是調用函數的問題,題意如下:
執行shell腳本,打印一個如下的水果菜單:
1.apple
2.pear
3.banana
4.cherry
當用戶輸入對應的數字選擇水果的時候,告訴他選擇的水果是什么,並給水果單詞加上一種顏色(隨意),要求用case語句實現。
解答如下:
顏色函數:
[root@m01 04 07:29:40]# cat 4-3.sh
#!/bin/bash
red="\033[31m" #定義紅色
green="\033[32m" #定義綠色
yellow="\033[33m" #定義黃色
blue="\033[34m" #定義藍色
tail="\033[0m" #定義顏色結尾
color(){ #定義顏色函數
case "$1" in
red)
echo -e "${red}$2${tail}"
;;
green)
echo -e "${green}$2${tail}"
;;
yellow)
echo -e "${yellow}$2${tail}"
;;
blue)
echo -e "${blue}$2 ${tail}"
;;
*)
echo "Usage:$0 arg1 arg2"
esac
}
color $* #調用函數
主要腳本,輸出結果:
[root@m01 04 07:31:05]# cat 4-2.sh
#!/bin/bash
. /server/scripts/04/4-3.sh #調用另外一個腳本
cat<<EOF
1.apple
2.pear
3.banana
4.cherry
EOF
usage(){
echo "Usage:$0 {1|2|3|4}"
}
#. /server/scripts/04/4-3.sh
selectfruits(){
read -p "pls select fruits nums:" num
case "$num" in
1)
color red apple #由4-3.sh來提供參數值,父子函數
;;
2)
color green pear
;;
3)
color yellow banana
;;
4)
color blue cherry
;;
*)
usage
exit 1
esac
}
main(){
#if [ $# -ne 1 ];then
# usage
#fi
selectfruits
}
main $*
得到結果