linux之shell编程之case学习

       case语句

结构上更明晰的多分支


case SWITCH in

value1)

   statement

   ..

   ;;

value2)

   statement

   ..

   ;;

*)

   statement

   ..

   ;;

esac


脚本1:case.sh
#!/bin/bash
#
case $1 in
[0-9])
    echo "A digit." ;;
[a-Z])
    echo "Lower" ;;
[A-Z])
    echo "Upper" ;;
*)
    echo "special charcter." ;;
esac


脚本2:revice.sh
#!/bin/bash
#
case $1 in
start)
    echo "starting server..." ;;
stop)
    echo "stopping server..." ;;
restart)
    echo "restarting server..." ;;
status)
    echo "running..." ;;
*)
    echo "Usage:`basename $0` (start|stop|restart|status)" ;;
esac


题目:写一个脚本,可以接受选项及参数,而后能获取每一个选项,及选项参数,并能根据选项和参数做出特定的操作。

比如:adminusers.sh -add tom,jerry --del tom,blair -v|--verbose -h|--help

#!/bin/bash
#
DEBUG=0
ADD=0
DEL=0
for I in `seq 0 $#`;do
    if [ $# -gt 0];then
        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 ;;
        *)
            echo "Usage:`basename $0` -add USER_LIST --del USER_LIST -v|--verbose -h|--help"
            exit 7
            ;;
        esac
    fi
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 exists."
        fi
    done
fi


脚本练习: showlogged.sh -c -v -h|--help

#!/bin/bash
#
declare -i SHOWNUM=0
declare -i SHOWUSER=0
for I in `seq 0 $#`;do
    if [ $# -gt 0 ];then
        case $1 in
        -h|--help)
            echo "Usage:`basename $0` -h|--help -c|--counts -v|--verbose"
            exit 0 ;;
        -v|--verbose)
            let SHOWUSER=1
            shift ;;
        -c|--counts)
            let SHOWNUM=1 ;;
            shift ;;
        *)
            echo "Usage:`basename $0` -h|--help -c|--counts -v|--verbose"
            exit 8 ;;
        esac
    fi
done
if[ $SHOWNUM -eq 1 ];then
    echo "Logged users:`who |wc -l`"
    if[ $SHOWUSER -eq 1 ];then
        echo "They are:" who
    fi
fi


你可能感兴趣的:(linux,server,special,starting)