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"shell最简单脚本
;;
esac
}
for i in $( seq110)
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:          1869165170302148
-/+ buffers/cache:        961773
Swap:        199901999
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 限制等待输⼊时长等

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。