关于shell中函数调用的理解

今天做一个试题就是调用函数的问题,题意如下:

执行shell脚本,打印一个如下的水果菜单:

1.apple

2.pear

3.banana

4.cherry

当用户输入对应的数字选择水果的时候,告诉他选择的水果是什么,并给水果单词加上一种颜色(随意),要求用case语句实现。

解答如下:

  颜色函数:

[root@m01 04 07:29:40]# cat 4-3.sh
#!/bin/bash
red="33[31m"  #定义红色
green="33[32m"  #定义绿色
yellow="33[33m"  #定义黄色
blue="33[34m"  #定义蓝色
tail="33[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 $*

得到结果

原文地址:https://www.cnblogs.com/wang50902/p/10932750.html