shell编程基础(4)case 与 function

case

case语句不用多说和c++里一样,用作选择,但是linux的case语句在语法上和c++还是有些不同的。

###########This is program test the Case##################
########   cxz   #############  2015 5 12  ###############
read -p "type in 1 2 3, nothing more " input;
case $input in
    "1")
    echo " the num is first in natural num"
    ;;
    "2")
    echo " the num is second in natural num"
    ;;
    "3")
    echo " the num is the third in natural num"
    ;;
    "")
    echo " are you ok? I got nothing"
    ;;
    *)
    echo "illegal input"
    ;;
esac

这里要注意的是通配符,是不加“”的,之前我在写的时候写成了“”)就出现了错误导致’illegal input’无法执行。
还有“$”)中的),这个单括号和后面’;;’是其他编程语言中很少见的部分,需要记住。可以这样记,第一个;对应的是所实行的语句结束,第二个;对应的是case命令结束,相当于c中的break。

function

function 功能是编程中非常重要的一部分,尤其是面向过程的编程方法就是以各种 function组合实现的。同样shell编程也提供了利用function 来组织程序的思路

###########This is test for the function #########
####### cxz ######## 2015 5 12 ###################
function printit(){
    echo  "your choice is $1"
}

read -p "put in your choice  " choice
case $choice in
    "one")
    printit 1
    ;;
    "two")
    printit 2
    ;;
    "three")
    printit 3
    ;;
    *)
    printit error
esac

这是利用打印函数printit来输出数据。其中在priniti里使用了“$1”这样的标记方法,这里的$1指的是printit函数的第一个参数,而不是整个shell的第一个参数,这里需要注意。

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/ironstark/p/4892640.html