case语句:选择结构
case SWITCH in
value1 )
statement
…
;;
value2)
statement
…
;;
*)
statement
…
;;
esac
写一个脚本显示用户输入的1个字符是字母或者是数字等。
#!/bin/bash
#
case $1 in
[0-9])
echo ‘shuzi‘
;;
[a-z])
echo ‘xiaoxiezimu‘
;;
[A-Z])
echo ‘daxiezimu‘
;;
*)
echo ‘teshuzifu‘
;;
esac
写一个脚本,可以接受选项及参数,而后能获取每一个选项,及选项的参数:并能根据选项及参数做出特定的操作。比如:adminusers.sh --add tom,jerry–del tom,blair –v|--verbose –h |--help
#!/bin/bash
#
DEBUG=0
DEL=0
ADD=0
for I in `seq 1 $#`;do
if [ $# -gt 0 ];then
case $1 in
-v|--verbose)
DEBUG=1
shift
;;
-h|--help)
echo "Usage: `basename $0` --addUSER_LIST --del USER_LIST –v|--verbose–h |--help."
exit 0
;;
--add)
ADD=1
ADDUSERS=$2
shift 2
;;
--del)
DEL=1
DELUSERS=$2
shift 2
;;
*)
echo "Usage: `basename $0` --addUSER_LIST --del USER_LIST.v|--verbose h |--help."
exit 6
;;
esac
fi
done
if [ $ADD -eq 1 ];then
forUSER in `echo $ADDUSERS | sed ‘[email protected],@ @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
forUSER in `echo $DELUSERS | sed ‘[email protected],@ @g‘`; do
if id $USER &> /dev/null;then
userdel -r $USER
[ $DEBUG -eq 1 ] && echo "Delete $USER finnished."
else
[ $DEBUG -eq 1 ] && echo "$USER not exists."
fi
done
fi
写一个脚本showlogged.sh,其用法格式为:
Showlogged.sh –v –c –h|--help 其中,-h选项只能单独使用,用于显示帮助信息:-c选项时,显示当前系统上登录的所有用户数;如果同时使用-v选项,则既显示同时登录的用户数,又显示登录的用户的相关信息。
#!/bin/bash
#
declare -i SHOWNUM=0
declare -i SHOWUSERS=0
for I in `seq 1 $#`;do
case $1 in
-v)
SHOWUSERS=1
shift
;;
-c)
SHOWNUM=1
shift
;;
-h|--help)
echo "Usage:`basename $0sh` -h|--help|-c|-v"
exit 0
;;
*)
echo "Usage:`basename $0sh` -h|--help|-c|-v"
exit 2
;;
esac
done
if [ $SHOWNUM -eq 1 ];then
echo "Loged users: `who | wc -l`."
if[ $SHOWUSERS -eq 1 ] ;then
echo "They are:"
who
fi
fi