标签:case
选择执行的三种方式:
(1) &&, ||
(2) if语句
(3) case语句
case语句的语法格式:
case $VARAIBLE in
PAT1)
分支1
;;
PAT2)
分支2
;;
...
*)
分支n
;;
esac
case支持glob风格的通配符:
*:任意长度的任意字符;
?:任意单个字符;
[]:范围内任意单个字符;
a|b:a或b;
示例:写一个服务框架脚本;
$lockfile, 值/var/lock/subsys/SCRIPT_NAME
(1) 此脚本可接受start, stop, restart, status四个参数之一;
(2) 如果参数非此四者,则提示使用帮助后退出;
(3) start,则创建lockfile,并显示启动;stop,则删除lockfile,并显示停止;restart,则先删除此文件再创建此文件,而后显示重启完成;status,如果lockfile存在,则显示running,否则,则显示为stopped.
#!/bin/bash # # chkconfig: - 50 50 # description: test service script # prog=$(basename $0) lockfile=/var/lock/subsys/$prog case $1 in start) if [ -f $lockfile ]; then echo "$prog is running yet." else touch $lockfile [ $? -eq 0 ] && echo "start $prog finshed." fi ;; stop) if [ -f $lockfile ]; then rm -f $lockfile [ $? -eq 0 ] && echo "stop $prog finished." else echo "$prog is not running." fi ;; restart) if [ -f $lockfile ]; then rm -f $lockfile touch $lockfile echo "restart $prog finished." else touch -f $lockfile echo "start $prog finished." fi ;; status) if [ -f $lockfile ]; then echo "$prog is running" else echo "$prog is stopped." fi ;; *) echo "Usage: $prog {start|stop|restart|status}" exit 1 esac
事例:
写一个脚本
(1) 列出如下菜单给用户:
disk) show disks info;
mem) show memory info;
cpu) show cpu info;
*) quit;
(2) 提示用户给出自己的选择,而后显示对应其选择的相应系统信息;
if语句的写法:
#!/bin/bash # cat << EOF disk) show disks info mem) show memory info cpu) show cpu info *) QUIT EOF read -p "Your choice: " option if [[ "$option" == "disk" ]]; then fdisk -l /dev/[sh]d[a-z] elif [[ "$option" == "mem" ]]; then free -m elif [[ "$option" == "cpu" ]];then lscpu else echo "Unkown option." exit 3 fi
本文出自 “汪立明” 博客,请务必保留此出处http://afterdawn.blog.51cto.com/7503144/1915996
标签:case
原文地址:http://afterdawn.blog.51cto.com/7503144/1915996