case命令简介:
此命令用于条件判断,选择结构.
1.命令格式:
case SWITCH in -----SWITCH 变量值
value1)
statement -----statement 语句
...
;;
value2)
statement
...
;;
*)
statement
....
;;
esac
2.命令功能:
通过选择结构,对所有可能出现的条件语句,进行比较得出最后输出结果。
3.命令参数:
/
4、命令实例:
1、通过键盘输入字符,如果是大写字母就表示大写字母,小写即为小写字母。
#!/bin/bash
#
case $1 in
[0-9])
echo "it is digit"
;;
[a-z])
echo "it is lower"
;;
[A-Z])
echo "it is Upper"
;;
*)
echo "it is Unknown"
;;
esac
2、只接受参数start ,stop,restart,shutdown.
#!/bin/bash
#
#program
case $1 in
‘start‘)
echo "start server..." ;;
‘restart‘)
echo "restart server..." ;;
‘stop‘)
echo "stop server..." ;;
‘status‘)
echo "Running..." ;;
*)
echo "`basename $0` {start|stop|restart|status}" ;;
esac
3、写一个脚本,可以接受选项参数,而后能获取每一个选项,及选项的参数,
并能根据选项及参数做出特定的操作。
#!/bin/bash
#
declare -i SHOWNUM=0
declare -i SHOWUSERS=0
for I in `seq 1 $#`; do
if [ $# -gt 0 ]; then
case $1 in
-h|--help)
echo "Usage: `basename$0` -h|--help -c|--count -v|--verbose"
exit 0 ;;
-v|--verbose)
let SHOWUSERS=1
shift ;;
-c|--count)
let SHOWNUM=1
shift ;;
*)
echo "Usage: `basename$0` -h|--help -c|--count -v|--verbose"
exit 8 ;;
esac
fi
done
if [ $SHOWNUM -eq 1 ]; then
echo "Logged users: `who |wc -l`."
if [ $SHOWUSERS -eq 1 ]; then
echo "They are:"
who
fi
fi