shell脚本中case的用法

 shell脚本中case选择语句可以结合read指令实现比较好的交互应答操作,case接收到read指令传入的一个或多个参数,然后case根据参数做选择操作。

 case的语法如下

 

case  $char  in
 
        C | c )
                command 1
                ;;          #每一个选择都以双 ;; 结束
        M | m )
                command 2
                ;;
            *   )               #  * 未匹配到相符的其他值                                                                                                                                                                 
                echo  “error”
               ;;

esac           #case的结束语句是以esac 结束

 

下面结合一个简单的小功能使用,脚本中同时也用到了函数的方法;简单查看系统信息

 

#!/bin/bash
echo "check system run status"
echo "show CPUinfo: C/c "
echo "show Memery used: M/m "
echo "show Disk use status: D/n "
echo "show System user login: U/n "
echo "show System load average:L/l"
echo "show System Ip address: I/i"

read_input () {
read  -t 10 -p "please Input C/M/D/U/L/I : " char
}

show_status () {

case $char in 
        
        C | c )
                cat /proc/cpuinfo | grep -o -i 'model name.*'
                ;;
        M | m )
                free -m
                ;;
        D | d )
                df -h
                ;;
        U | u )
                w
                ;;
        L | l )
                top | head -1 | cut -d " " -f 11-15
                ;;
        I | i )
                ifconfig | grep -o "[0-9.]\{7,\}" | head -1
                ;;
        * )
                echo "The characters you have entered are wrong. Please look at the hints"
                ;;
esac
}


for i in $( seq 1 10)
do
read_input
show_status
if [ $i -eq 10 ]; then
        echo "已经到达查询的最大次数,脚本退出;"
fi
done

看看测试结果

[root@yufu home]# ./test.sh 
check system run status
show CPUinfo: C/c 
show Memery used: M/m 
show Disk use status: D/n 
show System user login: U/n 
show System load average:L/l
show System Ip address: I/i
please Input C/M/D/U/L/I : The characters you have entered are wrong. Please look at the hints
please Input C/M/D/U/L/I : m
             total       used       free     shared    buffers     cached
Mem:          1869        165       1703          0         21         48
-/+ buffers/cache:         96       1773
Swap:         1999          0       1999
please Input C/M/D/U/L/I : c
model name    : Intel(R) Core(TM) i5-3317U CPU @ 1.70GHz
model name    : Intel(R) Core(TM) i5-3317U CPU @ 1.70GHz
please Input C/M/D/U/L/I :

 


这样可以实现交互式地传递参数,并且通过循环可以设置选择次数,通过read  -t 限制等待输入时长等

posted on 2018-04-13 21:25  孤岛鱼夫  阅读(18828)  评论(0编辑  收藏  举报