case语句结构:
case SWITCH in
value1)
statement
...
;;
value2)
statement
...
;;
*)
statement
...
;;
esac
联系:
1.接受从键盘上输入的字符,并作出判断是数字、大小写字母或特殊字符。
#!/bin/bash
case $1 in
[0-9])
echo "a digit"
;;
[A-Z])
echo "a Upper"
;;
[a-z])
echo "a Lower"
;;
*)
echo "a Special"
;;
esac
2.写一个脚本,接受参数 start,stop、restart,status其中之一,并输出接受的参数。
#!/bin/bash
case $1 in
start)
echo "start"
;;
stop)
echo "stop"
;;
restart)
echo "restart"
;;
status)
echo "status"
;;
*)
echo "Usage:`basename $0` (start|stop|restart|status)";;
esac
3.写一个脚本,可以接受选项及参数,而后能获取每一个选项及选项的参数,并能根据选项的参数做出特定的操作。例如:
test.sh --add tom --del --tom -v|--verbose -h|--hep
#!/bin/bash
DEBUG=0
ADD=0
DEL=0
for I in `seq 0 $#`;do
if [ $# -ge 0 ];then
case $1 in
-v|--verbose)
DEBUG=1
shift
;;
-h|--help)
echo "Usage: `basename $0` -add USER --del USER -v|--verbose -h|--help
"
exit 0
;;
--add)
ADD=1
ADDUSERS=$2
shift 2
;;
--del)
DEL=1
DELUSERS=$2
shift 2
;;
*)
echo "Usage: `basename $0` -add USER --del USER -v|--verbose -h|--help"
exit 7;;
esca
fi
done
if [$ADD -eq 1];then
for USERS in `echo $ADDUSERS |sed ‘s@,@@g‘`;do
if id $USERS &> /dev/null;then
[$DEBUG -eq 1] && "$USERS exists"
else
useradd $USERS
[$DEBUG -eq 1] && "$USERS add ok!"
fi
done
fi
if [$DEL -eq 1];then
for USERS in `echo $DELUSERS |sed ‘s@,@@g‘`;do
if id $USERS &> /dev/null;then
userdel -r $USERS
[$DEBUG -eq 1] && "$USERS del ok!"
else
[$DEBUG -eq 1] && "$USERS not exists!"
fi
done
fi
4.写一个脚本showlogged.sh,其语法格式为:
showlogged.sh -v -c -h|help
其中,-h选项只能单独使用,用于显示帮助信息,-c|--count 选项显示当前系统上登陆的所有用户的总个数。如果同时使用了-v|--verbose 选项,则既显示同时登陆的用户数,又显示登陆的用户的相关信息。如:
Logged users:4、
they are:
root tty2 Feb 10 02:41
root pts/1 Mar 8 08:36 (172.16.100.177)
root pts/5 Mar 8 07:56 (172.16.100.177)
hadoop pts/5 Mar 8 09:16 (172.16.100.177)
#!/bin/bash
declare -i USUM=0
declear -i SHOWUSERS=0
for I in `seq 0 $#`;do
if [ $# -ge 0 ];then
case $1 in
-h|--help)
echo "Usage `basename $0` -v -c -h|--help"
exit 0
;;
-v|--verbose)
let SHOWUSERS=1
shift
;;
-c|--conut)
let USUM=1
shift
;;
*)
echo "Usage `basename $0` -v -c -h|--help"
exit 7
;;
esac
fi
done
if [ $USUM -eq 1 ];then
echo "Logged users:`who|wc -l`."
fi
if [ $SHOWUSERS -eq 1 ];then
echo "they are:"
who
fi
本文出自 “小私的blog” 博客,请务必保留此出处http://ggvylf.blog.51cto.com/784661/1604824
case语句