shell脚本中case的用法

时间:2024-06-28 15:03:26

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

case的语法如下

case  $char  in

        C | c )
command
;; #每一个选择都以双 ;; 结束
M | m )
command
;;
* ) # * 未匹配到相符的其他值
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 -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 - | cut -d " " -f -
;;
I | i )
ifconfig | grep -o "[0-9.]\{7,\}" | head -
;;
* )
echo "The characters you have entered are wrong. Please look at the hints"
;;
esac
} for i in $( seq )
do
read_input
show_status
if [ $i -eq ]; 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:
-/+ buffers/cache:
Swap:
please Input C/M/D/U/L/I : c
model name : Intel(R) Core(TM) i5-3317U CPU @ .70GHz
model name : Intel(R) Core(TM) i5-3317U CPU @ .70GHz
please Input C/M/D/U/L/I :

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