2023年7月10日发(作者:)
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/bashecho "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)doread_inputshow_statusif [ $i -eq 10 ]; then echo "已经到达查询的最⼤次数,脚本退出;"fidone看看测试结果[root@yufu home]# ./
check system run statusshow 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/lshow System Ip address: I/iplease Input C/M/D/U/L/I : The characters you have entered are wrong. Please look at the hintsplease Input C/M/D/U/L/I : m total used free shared buffers cachedMem: 1869 165 1703 0 21 48-/+ buffers/cache: 96 1773Swap: 1999 0 1999please Input C/M/D/U/L/I : cmodel name : Intel(R) Core(TM) i5-3317U CPU @ 1.70GHzmodel name : Intel(R) Core(TM) i5-3317U CPU @ 1.70GHzplease Input C/M/D/U/L/I :
这样可以实现交互式地传递参数,并且通过循环可以设置选择次数,通过read -t 限制等待输⼊时长等
发布者:admin,转转请注明出处:http://www.yc00.com/news/1688986591a191861.html
评论列表(0条)