首页 > 系统服务 > 详细

shell脚本中case的用法

时间:2018-04-13 21:56:22      阅读:244      评论:0      收藏:0      [点我收藏+]

 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 限制等待输入时长等

shell脚本中case的用法

原文:https://www.cnblogs.com/anay/p/8824089.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!