面向过程
控制结构
顺序结构
选择结构
循环结构
选择结构:
if:单分支、双分支、多分支
cese语句:选择结构
case SWITCH in
value1)
statemnet
...
;;
value2)
statement
...
;;
*)
statement
...
;;
esac
[0-9] [a-z] [A-Z] [abc]
#!/bin/bash
#
case $1 in
[0-9])
echo "a digit";;
[a-z])
echo "Lower";;
[A-Z])
echo "upper";;
*)
echo "special character.";;
esac
只接受参数start,stop,restart,status其中之一
#!/bin/bash
#
case $1 in
‘start‘)
echo "start server ...";;
‘stop‘)
echo "stop server ...";;
‘restart‘)
echo "restart server ...";;
‘status‘)
echo "running ...";;
*)
echo "`basename $0` {start|stop|restart|status}";;
esac
写一个脚本,可以接受选项及参数,而后能获取每一个选项,及选项的参数,并能根据选项及参数做出特定的操作,比如
demo.sh --add tom,jerry --del tom,blair -v|--verbose -h|--help
#!/bin/bash
#
DEBUG=0
ADD=0
DEL=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` --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 USERS 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
for USER in `echo $DELUSERS | sed ‘[email protected],@ @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
练习:写一个脚本
demo.sh -v -c -h|--help
其中,-h选项只能单独只用,用于显示帮助信息;-c选项时,显示当前系统上登陆的所有用户数;如果同时使用了-v选项,则既显示同时登陆的用户数,又显示登陆的用户的相关信息,如
Logged users: 4.
They are:
root tty2 Feb 18 02:41
root pts/1 Mar 8 08:36 (172.19.49.88)
root pts/5 Mar 8 08:36 (172.19.49.88)
hadoop pts/6 Mar 8 08:36 (172.19.49.88)
#!/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 |--counts -v|--verbose"
exit 0
;;
-v|--verbose)
let SHOWUSERS=1
shift;;
-c|--count)
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 [ $SHOWUSERS -eq 1 ]; then
echo "They are:"
who
fi
fi