标签:case语句
一、使用$random变量随机取10个随机数,进行最大值和最小值对比
#!/bin/bash # declare -i MAX=0 for I in {1..10};do MYRANDOM=$RANDOM [ $I -eq 1 ] && MIN=$MYRANDOM; if [ $I -le 9 ];then echo -n "$MYRANDOM," else echo "$MYRANDOM" fi [ $MYRANDOM -gt $MAX ] && MAX=$MYRANDOM [ $MYRANDOM -lt $MIN ] && MIN=$MYRANDOM done echo "The Max is $MAX" echo "The Min is $MIN"
面向过程的编程:
控制结构:
顺序结构
选择结构
循环结构
选择结构:
if:单分支、双分支、多分支
if CONDITION;then
statment
....
else CONDITION;then
statment
...
fi
if CONDITION;then
statment
....
elif CONDITION;then
statment
...
else CONDITION;then
statment
...
fi
case 语句:选择结构,格式如下
case SWITCH in {变量(引用变量值)}
value1)
statment
...
;;
value2)
statment
...
;;
*)
statment
...
;;
esac
例:
#!/bin/bash # case $1 in [0-9]) echo "This is a digit.";; [a-z]) echo "This is a aha.";; [A-Z]) echo "This is a upper.";; *) echo "this is a Special character.";; esac ~
#!/bin/bash # case $1 in ‘start‘) echo "start server...";; ‘stop‘) echo "stop server...";; ‘status‘) echo "Running...";; ‘restart‘) echo "restart server...";; *) echo "`basename $0` start,stop,restart,status";; esac
写一个脚本,可以接受选项及参数,而后能获取每一个选项,及选项的参数,并能根据选项及参数做出特定的操作,比如:adminiusers.sh --add user1,user2,user3 --del user2,user3 -v|--verbose -h|--help
#!/bin/bash # DEBUG=0 ADD=0 DEL=0 for I in `seq 0 $#`;do case $1 in -v|--verbose) DEBUG=1 shift ;; -h|--help) echo "Usage:`basename $0` --add USER_LIST --del USER_LIST -v|--verbose -h|--help" exit 0 ;; --add) ADD=1 ADDUSERS=$2 shift 2 ;; --del) DEL=1 DELUSERS=$2 shift 2 ;; esac done if [ $ADD -eq 1 ];then for USER in `echo $ADDUSERS | sed ‘s/,/ /g‘`;do if id $USER &> /dev/null;then [ $DEBUG -eq 1 ] && echo "$USER exists." else useradd $USER [ $DEBUG -eq 1 ] && echo "Add user $USER finished." fi done fi if [ $DEL -eq 1 ];then for USER in `echo $DELUSERS | sed ‘s/,/ /g‘`;do if id $USER &> /dev/null;then userdel -r $USER [ $DEBUG -eq 1 ] && echo "Delete $USER finished." else [ $DEBUG -eq 1 ] && echo "$USER not exist." fi done fi
标签:case语句
原文地址:http://leozhenping.blog.51cto.com/10043183/1634914